Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make my Thread pool create its threads as foreground?

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

like image 472
RollRoll Avatar asked Jan 31 '13 17:01

RollRoll


2 Answers

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.

like image 161
Hans Passant Avatar answered Oct 14 '22 06:10

Hans Passant


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");
like image 32
Boppity Bop Avatar answered Oct 14 '22 05:10

Boppity Bop