EN
C#/.NET - Foreground & Background Threads
5
points
In this article, we would like to show how to create foreground and background threads in C# / .NET.
Foreground vs Background thread:
- Foreground thread is threads that is still executed after main thread stopped working
(that threads prevent a process from terminating).- 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.