简体   繁体   中英

new Thread() and Threadpool?

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

ps (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).)

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.

The IsBackground property does not do what you think it does. It is merely a flag that tells the CLR whether it is okay to abort the thread when the non-background threads complete, including the main thread of the program. If it is false , the default value, then the CLR won't interfere with the thread, allowing it to complete. Setting it to true invokes the equivalent of Thread.Abort(), minus the ability for the thread to do anything about it or be notified about it. A rude abort.

The thread created by the Thread class is never pooled, unless some kind of custom CLR host is used which is very rare. Common ways to create a threadpool thread are ThreadPool.QueueUserWorkItem,() BackgroundWorker, a delegate's BeginInvoke() method and the Task class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM