TPL - set Task to Thread.Sleep for a long time

自古美人都是妖i 提交于 2019-12-24 11:06: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?


回答1:


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());

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



来源:https://stackoverflow.com/questions/8237083/tpl-set-task-to-thread-sleep-for-a-long-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!