Languages
[Edit]
EN

C#/.NET - Foreground & Background Threads

5 points
Created by:
martineau
990

In this article, we would like to show how to create foreground and background threads in C# / .NET.

Foreground vs Background thread:

  1. Foreground thread is threads that is still executed after main thread stopped working
    (that threads prevent a process from terminating).
  2. Background thread is threads that ends execution when main thread stops execution.

Quick solution:

// using System.Threading;

Thread thread = new Thread(() =>
{
    // put some source code here ...
});

// thread.IsBackground = true;   // background thread 
// thread.IsBackground = false;  // foreground thread (by default is false)

thread.Start();

 

1. Foreground thread example

using System;
using System.Threading;

namespace Test
{
	public class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Main thread started...");

			Thread thread = new Thread(() =>
			{
				Console.WriteLine("My foreground thread started...");
				Thread.Sleep(1000);
				Console.WriteLine("My foreground thread stopping...");
			});

			thread.IsBackground = false;
			thread.Start();

			Thread.Sleep(500);
			Console.WriteLine("Main thread stopping...");
		}
	}
}

Output:

Main thread started...
My foreground thread started...
Main thread stopping...
My foreground thread stopping.

Summary:

My foreground thread ended execution after main thread ended.

 

2. Background thread example

using System;
using System.Threading;

namespace Test
{
	public class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Main thread started...");

			Thread thread = new Thread(() =>
			{
				Console.WriteLine("My background thread started...");
				Thread.Sleep(1000);
				Console.WriteLine("My background thread stopping...");
			});

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

			Thread.Sleep(500);
			Console.WriteLine("Main thread stopping...");
		}
	}
}

Output:

Main thread started...
My foreground thread started...
Main thread stopping...

Summary:

My foreground thread stopping... was never printed because bacground thread ended with main thread.

 

References

  1. Thread.IsBackground Property - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# - Thread Class

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join