TPL-将Task设置为Thread.Sleep很长时间
我有一个使用.NET任务并行库的测试:有
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小时)会有什么缺点吗?
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
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样就会占用ThreadPool中的一个线程。尝试运行代码,你会发现整个线程池都被等待的任务占用了。使用:
ParallelExtensionsExtras 项目包含一个名为 StartNewDelayed 的 TaskFactory 扩展方法,您可以在其中安排任务。请参阅:http://geekswithblogs.net/JoshReuben/archive /2010/11/14/parallel-extensions-extras.aspx
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:
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