问题描述
试图抓住TPL。
只是为了好玩,我试着创建一些任务随机睡眠,看看它是如何处理的。我是针对一个火和忘记模式。
static void Main(string [] args)
{
Console.WriteLine(演示成功的事务);
Random d = new Random();
for(int i = 0; i {
var sleep = d.Next(100,2000);
Action< int> succes =(int x)=>
{
Thread.Sleep(x);
Console.WriteLine(sleep = {2},Task = {0},Thread = {1}:Begin successful transaction,
Task.CurrentId,Thread.CurrentThread.ManagedThreadId,x);
};
任务t1 = Task.Factory.StartNew(()=> succes(sleep));
}
Console.ReadLine();
}
但我不明白为什么它输出所有行到控制台忽略睡眠(随机)
有人可以向我解释吗?
重要:
TPL默认TaskScheduler不保证每个任务的线程 - 一个线程可用于处理多个任务。
$ b $
您可以使用 TaskCreationOptions.LongRunning
来构建任务。 / em>提示这样TaskScheduler将为任务分配一个专用的线程,它将安全地阻止它。trying to grasp the TPL.
Just for fun I tried to create some Tasks with a random sleep to see how it was processed. I was targeting a fire and forget pattern..
static void Main(string[] args)
{
Console.WriteLine("Demonstrating a successful transaction");
Random d = new Random();
for (int i = 0; i < 10; i++)
{
var sleep = d.Next(100, 2000);
Action<int> succes = (int x) =>
{
Thread.Sleep(x);
Console.WriteLine("sleep={2}, Task={0}, Thread={1}: Begin successful transaction",
Task.CurrentId, Thread.CurrentThread.ManagedThreadId, x);
};
Task t1 = Task.Factory.StartNew(() => succes(sleep));
}
Console.ReadLine();
}
But I don't understand why it outputs all lines to the Console ignoring the Sleep(random)
Can someone explain that to me?
Important:
The TPL default TaskScheduler does not guarantee Thread per Task - one thread can be used for processing several tasks.
Calling Thread.Sleep might impact other tasks performance.
You can construct your task with the TaskCreationOptions.LongRunning hint this way the TaskScheduler will assign a dedicated thread for the task and it will be safe to block on it.
这篇关于任务忽略Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!