Royi Namir
Royi Namir

Reputation: 148514

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

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

Upvotes: 2

Views: 1099

Answers (2)

Hans Passant
Hans Passant

Reputation: 941208

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.

Upvotes: 4

SLaks
SLaks

Reputation: 887195

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.

Upvotes: 7

Related Questions