Keywords: C# | Task | CancellationToken | Multithreading
Abstract: This article discusses how to properly cancel tasks in C# using System.Threading.Task, avoiding the discouraged Thread.Abort() method. It introduces the CancellationToken mechanism for cooperative cancellation, ensuring safety and control in multithreading. Key concepts, code examples, and best practices are covered.
Introduction
In C# multithreading, task cancellation is a common requirement. Users often attempt to use Thread.Abort() to terminate threads, but this is not suitable for tasks based on the thread pool and may lead to unpredictable behavior.
Tasks and Thread Pool
TPL (Task Parallel Library) tasks utilize background threads from the thread pool. Directly aborting threads can cause resource leaks and state inconsistencies, making the Abort() method not recommended for task cancellation.
CancellationToken Mechanism
The recommended approach is to use CancellationTokenSource and CancellationToken for cooperative cancellation. Tasks should periodically check the CancellationToken.IsCancellationRequested property and gracefully terminate when cancellation is requested.
Implementation Example
class Program
{
static void Main()
{
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
Console.WriteLine("task canceled");
break;
}
}
}, ct);
Thread.Sleep(3000);
ts.Cancel();
Console.ReadLine();
}
}
Best Practices and Considerations
Regularly check the cancellation token in long-running loops; avoid using the Abort method to prevent unstable states; handle cancellation exceptions to ensure program robustness.
Conclusion
CancellationToken provides a standard and safe way to cancel TPL tasks, enhancing the reliability of multithreaded applications through cooperative mechanisms.