views:

615

answers:

4

I am new to C#.I learnt that normally all threads are foreground until unless you explicitly specify it as "background" thread using IsBackGround= true .

Some doubts popped in to my mind.

1) What is the advantage of keeping a thread as background thread?

2) When executing the folowing code :

    static void Main(string[] args)
    {
        Thread worker = new Thread(SayHello);
        worker.IsBackground = true;
        worker.Start();
        Console.WriteLine("Hello From Main");
    }

    static void SayHello()
    {
        Console.WriteLine("Hello World");
        Console.ReadKey(true);
    }

i need to use worker.Join() to keep the main thread to wait as the program terminates immediately. Apart from Join() could i use other techniques to keep the main thread wait ?

+5  A: 

All it means is whether this thread will keep the process alive. If all the threads in your process are marked background then .Net will shut down your process and force it to exit.

In answer to your question, yes you have to join as the thread which is in the background will not keep it alive, thus when the startup thread leaves Main() then it will allow the application to exit.

Spence
+7  A: 

1) What is the advantage of keeping a thread as background thread?

The Advantage is that a Background Thread doesn't stop the Program from terminating. In a large Application it could be a bit hard to deactivate all threads if you want to quit the Application.

Apart from Join() could i use other techniques to keep the main thread wait?

If yo want to make the Main program wait why do you make the thread a background thread in the first place then??? Besides of Join() you could use a EventWaitHandle or Monitor to make the main method wait.

codymanix
+3  A: 

If the thread should complete before the program terminates, then it should not be a background thread.

There are lots of ways to make your main thread wait, but in the example above I think what you really want to do is to make sure it's not a background thread.

The Join method is generally used to make sure that threads are done executing before the calling thread continues. For example, you may spawn 5 threads that each do some math operation and the results of those operations may be needed to move on with the next step. The Join method will pause execution on the calling thread until the spawned threads can completed. It is important to note that if you call Join from the UI thread you will freeze your program until the spawned threads are finished.

In short, multi threading is really complicated and nuanced. I highly recommend buying a good book on the subject.

overstood
+1  A: 

You should read this Free E-Book on the subject http://www.albahari.com/threading/

Remi THOMAS