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

2019-08-06 02:53发布

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条回答
放荡不羁爱自由
2楼-- · 2019-08-06 03:41

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

查看更多
登录 后发表回答