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:
xxxxxxxxxx
1
// using System.Threading;
2
3
Thread thread = new Thread(() =>
4
{
5
// put some source code here ...
6
});
7
8
// thread.IsBackground = true; // background thread
9
// thread.IsBackground = false; // foreground thread (by default is false)
10
11
thread.Start();
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
public class Program
7
{
8
static void Main(string[] args)
9
{
10
Console.WriteLine("Main thread started...");
11
12
Thread thread = new Thread(() =>
13
{
14
Console.WriteLine("My foreground thread started...");
15
Thread.Sleep(1000);
16
Console.WriteLine("My foreground thread stopping...");
17
});
18
19
thread.IsBackground = false;
20
thread.Start();
21
22
Thread.Sleep(500);
23
Console.WriteLine("Main thread stopping...");
24
}
25
}
26
}
Output:
xxxxxxxxxx
1
Main thread started...
2
My foreground thread started...
3
Main thread stopping...
4
My foreground thread stopping.
Summary:
My foreground thread ended execution after main thread ended.
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
public class Program
7
{
8
static void Main(string[] args)
9
{
10
Console.WriteLine("Main thread started...");
11
12
Thread thread = new Thread(() =>
13
{
14
Console.WriteLine("My background thread started...");
15
Thread.Sleep(1000);
16
Console.WriteLine("My background thread stopping...");
17
});
18
19
thread.IsBackground = true;
20
thread.Start();
21
22
Thread.Sleep(500);
23
Console.WriteLine("Main thread stopping...");
24
}
25
}
26
}
Output:
xxxxxxxxxx
1
Main thread started...
2
My foreground thread started...
3
Main thread stopping...
Summary:
My foreground thread stopping...
was never printed because bacground thread ended with main thread.