Destroying and canceling threads
Aborting threads is not a good idea as you don’t always know the state of a thread. It can be made worse if the thread is part of a static constructor. Using Thread.Abort
to abort a thread is one of the main reasons for application crashes. The Thread.Abort
APIs are now obsolete. So, you are encouraged to use the cooperative cancellation pattern to periodically check for cancellations using CancellationToken
.
Under normal circumstances, when a thread is aborted, it is destroyed. The cancellation of a thread also destroys the thread. Let’s write some sample code that demonstrates the usage of CancellationToken
to cancel a synchronous operation when it times out, as follows:
- Start a new .NET 6 console application and call it CH14_Multithreading.
- In the Program.cs file of the CH14_Multithreading project, add the following method:
static bool TryCallWithTimeout<TResult>( Func<CancellationToken...