[C#] Multithreading in C# 3 [3] – Foreground and Background Threads

What is a foreground thread and a background thread? What are the differences? Let’s find out.

1. Foreground Threads and Background Threads

Let’s summarize what they are and how they differ:

  • Foreground Threads : The foreground tasks cannot be ignored and must be completed. CLR will not shut down an application until all foreground threads have ended.
  • Background Threads : The background tasks can be terminated at any time. When all foreground threads have terminated, any background threads can be aborted.

2. IsBackground Property

The “Thread” class provides the “IsBackground” property to set or set a value indicating whether or not a thread is a background thread.

public sealed class Thread
{
  public bool IsBackground { get; set; } // default is false
}

3. Creating Background Threads

It is easy to create a background thread. You just need to set the “IsBackground” property to true before starting the thread.

public static void Test1()
{
  Thread printPlus = new Thread(() =>
    {
      for (int i = 0; i < 1000; i++)
      {
        Console.Write("+ ");
        Thread.Sleep(1);
      }
    });

  printPlus.IsBackground = true;
  printPlus.Start();

  for (int j = 0; j < 20; j++)
  {
    Console.Write("- ");
    Thread.Sleep(1);
  }

  //printPlus.Join();
}

Note that the “Join()” method is commented out. The result will be quite surprising. As soon as “- ” is printed 20 times, the application is terminated. It does not wait until “+ ” is printed 1000 times.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s