Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Pool and .IsBackground in .NET

MSDN, as well as many other sources, claim that worker threads in the thread pool are always background.

"Thread pool threads are background threads." (MSDN)

"Pooled threads are always background threads." (Threading in C#, Joseph Albahari)

I can easily make the worker thread non-background by setting

Thread.CurrentThread.IsBackground = false;

And the application will be waiting until the thread finishes.

What's wrong with that?

like image 254
Dmitry Karpezo Avatar asked Sep 05 '10 17:09

Dmitry Karpezo


People also ask

What is thread pool in C#?

Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.

How many threads are in the thread pool C#?

ThreadPool can automatically increase or reduce the number of active threads to maximize task execution efficiency. The maximum allowed number of processing threads in a pool is 1023. The pool allocates a maximum of 1000 threads in an I/O operation.

Which method is used to determine whether the current thread is foreground?

IsBackground property to determine whether a thread is a background or a foreground thread, or to change its status. A thread can be changed to a background thread at any time by setting its IsBackground property to true .


3 Answers

Yes, you can change them. But you should not.

For the same reasons you don't repaint a borrowed car. Same for other thread properties like priority and MTA.

If you want a different kind of thread, create your own.

like image 156
Henk Holterman Avatar answered Oct 19 '22 10:10

Henk Holterman


When does the thread finish? When your method ends? I highly doubt that's the case. The whole point of the thread pool is that once your thread is finished, it gets put back in the pool to be reused. Now you've let go of a thread, it's gone back into the thread pool and your application is still running because it's a foreground thread. There's no way to get that thread back out to kill it.

like image 34
Hounshell Avatar answered Oct 19 '22 11:10

Hounshell


Thread pool threads are background threads

Finish that sentence with "they have their IsBackground property initialized to True, unlike threads created with the Thread class."

Setting it to false could be a bit risky. Threadpool threads are recycled, I'm not so sure that the property will be re-initialized. It is not a property associated with the physical operating system thread, they don't have IsBackground behavior, it is added by the wrapper that the CLR puts around it. So probably yes. Little reason to mess with it though.

like image 4
Hans Passant Avatar answered Oct 19 '22 09:10

Hans Passant