Languages
[Edit]
EN

C#/.NET - Foreground & Background Threads

2 points
Created by:
JustMike
3488

In C#/.NET it is possible to start foreground and background threads. Foreground threads are still executed after main thread stopped working in opposite to background threads which end execution when main thread ends execution.

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.
Note: 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 foreground thread started...");
				Thread.Sleep(1000);
				Console.WriteLine("My foreground 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...
Note: With main thread stop all background threads stop too ("My foreground thread stopping..." - has been never printed.).

3. References

  1. Thread.IsBackground Property - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.