In .NET Core, a CancellationToken is a mechanism for cancelling long-running operations. It is typically used in conjunction with asynchronous operations to allow the user to cancel a task that is taking too long to complete. A CancellationToken represents a request to cancel an operation, and can be passed to a method as a parameter.
To use a CancellationToken, you first create an instance of the CancellationTokenSource class, which provides a Token property that returns a CancellationToken. This token can then be passed to a method that supports cancellation, such as a Task.Run method that runs an asynchronous operation. Within the operation, you periodically check the IsCancellationRequested property of the CancellationToken to see if the user has requested cancellation. If cancellation has been requested, you can perform any necessary cleanup and return early from the operation.
Here is an example of how to use a CancellationToken:
public async Task DoWorkAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
// Perform work here
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
In this example, the DoWorkAsync method performs some long-running work in a loop. The cancellationToken parameter is passed in by the caller and is used to check if cancellation has been requested. The Task.Delay method is used to simulate the work being performed, but in a real application, this would be replaced with actual work.
No comments:
Post a Comment
Please keep your comments relevant.
Comments with external links and adult words will be filtered.