TPL - 将 Task 设置为 Thread.Sleep 很长时间 [英] TPL - set Task to Thread.Sleep for a long time
问题描述
我有一个使用 .NET 任务并行库的测试:
I have a test to use .NET Task Parallel Library:
static void Main(string[] args)
{
for(int i = 0; i < 1000; i++)
{
int n = i;
Task.Factory.StartNew(() => TaskTest(n));
}
}
static void TaskTest(int i)
{
// Will sleep for a long time
Thread.Sleep(TimeSpan.FromMinutes(i));
// Do something here
}
有一点我不确定:当上面代码中的 Thread.Sleep 执行时,会发生什么?我知道它不会占用 ThreadPool 中的一个线程,如果我将多个任务设置为 Thread.Sleep 24 小时之类的很长时间,是否有任何缺点?
One thing I'm not sure: When Thread.Sleep in the above code execute, what will happen? I know it will not occupy a thread in the ThreadPool, is there any drawback if I set multiple tasks to Thread.Sleep for a really long time like 24 hours?
推荐答案
这会占用 ThreadPool 中的一个线程.尝试运行代码,你会发现整个线程池都被等待的任务占用了.使用:
This will occupy a thread in the ThreadPool. Try running the code and you'll find out that the whole threadpool is occupied by tasks waiting. use:
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
{
int n = i;
tasks.Add(Task.Factory.StartNew(() => TaskTest(n)));
}
Task.WaitAll(tasks.ToArray());
ParallelExtensionsExtras 项目包含一个名为 StartNewDelayed 的 TaskFactory 扩展方法,您可以在其中安排任务.请参阅:http://geekswithblogs.net/JoshReuben/archive/2010/11/14/parallel-extensions-extras.aspx
the ParallelExtensionsExtras project contains an extension method for TaskFactory called StartNewDelayed, in which you can schedule a task. See: http://geekswithblogs.net/JoshReuben/archive/2010/11/14/parallel-extensions-extras.aspx
这篇关于TPL - 将 Task 设置为 Thread.Sleep 很长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!