Languages
[Edit]
EN

C#/.NET - stop thread (safe way)

14 points
Created by:
Zeeshan-Peel
730

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:

bool looped = true; // it is good to use volatile modifier too

Thread thread = new Thread(() =>
{
    // e.g.

	while(looped) // false value breaks loop
	{
		// put source code here and use `looped` variable to break it when needed ...
	}
});

// ...

looped = false; // false value breaks logic in thread (e.g. loop, conditions, etc.)

// ...

 

Practical example

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:

using System;
using System.Threading;

public class Program
{
	private static volatile bool looped = true; // volatile used to be sure if the value is always synchronized across threads

	public static void Main(string[] args)
	{
		Thread thread = new Thread(() =>
		{
			Console.WriteLine("Started");

			for (int i = 1; looped; ++i)
			{
				Console.WriteLine("Iteration: " + i);
				Thread.Sleep(300);
			}

			Console.WriteLine("Stopping");
		});

		Console.WriteLine("Starting");

		thread.Start();

		Thread.Sleep(1000);  // sleeps main thread for 1 seconds
		looped = false;      // false value breaks loop in the created thread

		thread.Join();       // sleeps main thread until created thread is not terminated

		Console.WriteLine("Stopped");
	}
}

Output:

Starting
Started
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Stopping
Stopped

Hint: to know how break thread that uses blocking methods read this article.

 

References

  1. Thread Class - Microsoft Docs
  2. Thread.Join method - Microsoft Docs

See also

  1. C#/.NET - create thread
  2. C#/.NET - thread join
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# - Thread Class

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join