By default the thread pool in .NET works with background threads.
I can't change it to run as foreground.
How do I change this to run as foreground threads?
Edit:
I need to use this because I'm changing my App due high volume processing (before it I was manually handling threads, which are Foreground ones by default), and I don't want to change my Application just to adapt it to a background threading scenario..
I'm wondering why Thread pool is not Foreground by default
The notion of a "background thread" means very little in .NET. The Thread.IsBackground property is just a simple flag that helps the CLR decide whether or not it should rudely abort the thread when the AppDomain gets unloaded or whether it should wait for the thread to exit voluntarily.
You can just change the property if you want a thread-pool thread to keep running at program exit. This snippet shows how that's possible:
using System;
using System.Threading;
class Program {
static void Main(string[] args) {
var sync = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem((_) => {
Console.WriteLine("Running");
Thread.CurrentThread.IsBackground = false;
sync.Set();
Thread.Sleep(5000);
Console.WriteLine("Done, should exit now");
Thread.Sleep(250);
});
sync.WaitOne(); // Ensures IsBackground is set
}
}
Do keep your eyes on the ball here. If this is important to you then there's a high likelihood you are doing something wrong.
You can set thread pool threads as foreground.
class Program
{
static void Main(string[] args)
{
new Action(() => Worker()).BeginInvoke(null,null);
Thread.Sleep(1000);
Console.WriteLine("Main ends here");
}
static void Worker()
{
Thread.CurrentThread.IsBackground = false;
Console.WriteLine("Worker started. Bg {0} Tp {1}.",
Thread.CurrentThread.IsBackground,
Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(5000);
Console.WriteLine("Worker ends here");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With