Best Practice: Handling CancellationTokenSource Correctly
CancellationTokenSource
Although classes can be released, the correct way to release them often confuses developers. This article dives into when and how to effectively release this class.
One of the reasons for this lack of clarity is that the CancellationTokenSource
class does not have a finalizer. This means that the garbage collector (GC) cannot free it automatically. Therefore, it becomes the developer's responsibility to explicitly release the token source.
Despite this, the examples provided on MSDN rarely mention releases. So, what is the recommended approach?
Release Strategy
Use 'using' statements when waiting for tasks to complete: If you are waiting for parallel tasks to complete, you can wrap your code with a 'using' statement. This ensures that the token source is automatically released after the task is completed:
using (CancellationTokenSource tokenSource = new CancellationTokenSource()) { Task.Run(() => { }, tokenSource.Token); }
Use ContinueWith and manual release: Alternatively, you can register a ContinueWith event handler on the task and manually release the token source in the handler:
Task.Run(async () => { try { // 任务代码 } finally { tokenSource.Dispose(); } }, tokenSource.Token);
Cancelable PLINQ queries: For cancelable PLINQ queries that are not returned synchronously, the recommended approach is to perform all operations in the CancellationTokenSource
event handler. Dispose
Reusability and multiple uses: Instances are not reusable. They should be created and released for every cancellation operation. CancellationTokenSource
Release directly: If you are unable to use a 'using' statement or a ContinueWith event handler, you can release the token source directly after it has served its purpose:
CancellationTokenSource tokenSource = new CancellationTokenSource(); Task.Run(() => { }, tokenSource.Token); // ... tokenSource.Dispose();
Summary
Freeing instances is critical to prevent memory leaks and ensure proper resource management. By adhering to the recommended release strategy, developers can handle cancellation operations efficiently in their code. CancellationTokenSource
The above is the detailed content of When and How Should I Dispose of a CancellationTokenSource?. For more information, please follow other related articles on the PHP Chinese website!