Languages
[Edit]
EN

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

14 points
Created by:
Zeeshan-Peel
850

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:

 

Practical example

Edit

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:

Output:

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

 

References

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

See also

Edit
  1. C#/.NET - create thread
  2. C#/.NET - thread join
1
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