Languages
[Edit]
EN

C#/.NET - stop thread (unsafe way with Thread Abort() method)

3 points
Created by:
Creg
9600

In this short article, we want to show you how to stop thread using Thread Abort() method in C# / .NET.

Warning: in .NET 5.0 Thread Abort() method was marked as deprecated and we shouldn't use that approach to stop threads.

The method presented in the article should be called an unsafe way to stop a thread, because was leading to many mistakes, requiring to have better knowledge of how to use it. Stopping the thread that way, we cannot predict during what operation the thread will be stopped. It may lead to losing consistency on objects shared across multiple threads.

Hint: go to this article to find safe way to stop thread.

 

Practical example:

Example output 1:

Example output 2:

 

Outputs summary:

In the output 1 case, we can see the difference between 4th and 5th lines (6552799 and 6552798).

In the output 2 case, we can see the difference in the 9th line (6724366 and 6724365).

 

Final conclusion:

While different run, the thread was stopped at a different moment in the middle of IncrementValues(counters) method, which makes it difficult to predict the final object state.

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.
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