EN
C#/.NET - stop thread (safe way)
14 points
In this short article, we want to show you how to stop thread in a safe way in C# / .NET.
The solution presented in the article can be called "safe stop". It guarantees termination the way the developer intended. It is achieved by using a variable that tells when the thread should stop.
Quick solution:
xxxxxxxxxx
1
bool looped = true; // it is good to use volatile modifier too
2
3
Thread thread = new Thread(() =>
4
{
5
// e.g.
6
7
while(looped) // false value breaks loop
8
{
9
// put source code here and use `looped` variable to break it when needed ...
10
}
11
});
12
13
// ...
14
15
looped = false; // false value breaks logic in thread (e.g. loop, conditions, etc.)
16
17
// ...
In this section, looped
variable is used to hold the loop in progress inside thread. When the variable value is changed to false
the thread ends execution in safe way.
Source code:
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
public class Program
5
{
6
private static volatile bool looped = true; // volatile used to be sure if the value is always synchronized across threads
7
8
public static void Main(string[] args)
9
{
10
Thread thread = new Thread(() =>
11
{
12
Console.WriteLine("Started");
13
14
for (int i = 1; looped; ++i)
15
{
16
Console.WriteLine("Iteration: " + i);
17
Thread.Sleep(300);
18
}
19
20
Console.WriteLine("Stopping");
21
});
22
23
Console.WriteLine("Starting");
24
25
thread.Start();
26
27
Thread.Sleep(1000); // sleeps main thread for 1 seconds
28
looped = false; // false value breaks loop in the created thread
29
30
thread.Join(); // sleeps main thread until created thread is not terminated
31
32
Console.WriteLine("Stopped");
33
}
34
}
Output:
xxxxxxxxxx
1
Starting
2
Started
3
Iteration: 1
4
Iteration: 2
5
Iteration: 3
6
Iteration: 4
7
Stopping
8
Stopped
Hint: to know how break thread that uses blocking methods read this article.