1

Why does a Thread (which I set IsBackgroundthread to True) is not running with the threadpool Threads ?

/*1*/   volatile bool r = false;
/*2*/   var g= new Thread(() => r=Thread.CurrentThread.IsThreadPoolThread );
/*3*/   g.IsBackground = true;
/*4*/   g.Start();
/*5*/   g.Join();
/*6*/   Console.WriteLine(r); //false

While this code (obviously) does run at a threadpool thread ?

 Task.Factory.StartNew(()=>Console.Write(Thread.CurrentThread.IsThreadPoolThread)); //true
 Console.ReadLine();

p.s. (I know that Task are (by default)run at a background threads and they run in a threadpool , but my question is about a similar situation where I set a thread to run at background).)

4

2 回答 2

7

The ThreadPool is a pool of dedicated threads managed by the runtime.

User-created background threads are not part of the threadpool.

In other words, all thread-pool threads are background threads, but not all background threads are thread-pool threads.

于 2013-06-27T14:32:02.323 回答
4

IsBackground 属性并不像您认为的那样做。它只是一个标志,告诉 CLR 在非后台线程(包括程序的主线程)完成时是否可以中止线程。如果它是默认值false,则 CLR 不会干扰线程,允许它完成。将其设置为true会调用 Thread.Abort() 的等效项,减去线程对其执行任何操作或收到通知的能力。粗鲁的中止。

Thread 类创建的线程永远不会被池化,除非使用某种非常罕见的自定义 CLR 主机。创建线程池线程的常用方法是 ThreadPool.QueueUserWorkItem,() BackgroundWorker、委托的 BeginInvoke() 方法和 Task 类。

于 2013-06-27T15:04:15.673 回答