开发者

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜