Languages
[Edit]
EN

C#/.NET - Foreground & Background Threads

2 points
Created by:
JustMike
26120

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join