为什么Thread.sleep代码影响的新任务创造? [英] Why Thread.Sleep affects creation of new Tasks?

查看:154
本文介绍了为什么Thread.sleep代码影响的新任务创造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private static void Main(string[] args)
{
    for (int i = 0; i < 1000; i++)
    {
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("hej");
            Thread.Sleep(10000);
        });    
    }
    Console.ReadLine();
}



为什么在一秒之后这段代码将无法打印1000次HEJ?为什么Thread.sleep代码(10000)对代码的行为产生影响?

Why this code won't print 1000 times "hej" after one second? Why Thread.Sleep(10000) has an impact on code behavior?

推荐答案

Factory.StartNew 有效委托的工作,以线程池

Factory.StartNew effectively delegates the work to ThreadPool.

线程池将创建的线程数立即作出回应只要线程计数小于或等于处理器计数请求。一旦达到处理器数量,线程池将停止创建新线程的立即的。这是有道理的,因为创建的线程数超过处理器数量介绍的线程调度的开销,并且没有返回。

Threadpool will create number of threads immediately to respond the request as long as threads count is less than or equal to processor count. Once it reaches processor count, threadpool will stop creating new threads immediately. That makes sense, because creating number of threads more than processor count introduces Thread scheduling overhead and returns nothing.

相反,它会节流线程的创建。它等待500毫秒,看是否有工作还悬而未决,没有线程来处理请求。如果挂起的作品都在那里,将引入一个新的线程(只有一个)。这个过程不断,只要你有足够的工作做准备。

Instead it will throttle the creation of threads. It waits for 500 ms to see if any work still pending and no threads to process the request. If pending works are there, it will introduce a new thread(only one). This process keeps on going as long as you have enough works to do.

在工作队列中的流量被清除,线程池会破坏线程。与上述过程不断持续。

When work queue's traffic is cleared, threadpool will destroy the threads. And above mentioned process keeps on going.

另外,还有一个的线程的线程池的数量最大限制可以同时运行。如果你打的,线程池将停止创建多个线程,并等待前期工作的项目来完成的,因此,它可以重复使用现有的线程。

Also, There is a max limit for number of threads threadpool can run simultaneously. If you hit that, threadpool will stop creating more threads and wait for previous work items to complete, So that it can reuse the existing thread.

这并不是故事的终结,这是令人费解!这是由线程池作出一些决定。

That's not the end of story, It is convoluted! These are few decisions taken by ThreadPool.

我现在希望你为什么看到你所看到的将是清楚的。

I hope now that will be clear why you see what you see.

这篇关于为什么Thread.sleep代码影响的新任务创造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆