Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

C#/.NET - Foreground & Background Threads

0 contributions
2 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more