Introduction
ASP.NET is a popular programming language used for building web applications. One common requirement in web development is the ability to cancel long-running operations. In this article, we will explore how to use the CancellationToken in ASP.NET controllers to handle cancellation requests.
What is a CancellationToken?
A CancellationToken is a mechanism provided by ASP.NET to allow the cancellation of long-running operations. It is typically used in scenarios where a user wants to cancel an ongoing operation, such as a file upload or a database query, before it completes.
Using CancellationToken in ASP.NET Controllers
When working with ASP.NET controllers, you can use the CancellationToken parameter in your action methods to handle cancellation requests. The CancellationToken parameter is automatically injected by the ASP.NET framework and provides a way to check if a cancellation has been requested.
public async Task LongRunningOperation(CancellationToken cancellationToken)
{
// Check if cancellation has been requested
if (cancellationToken.IsCancellationRequested)
{
// Handle cancellation logic
return StatusCode(400, "Operation cancelled by user");
}
// Perform long-running operation
await Task.Delay(5000);
return Ok("Operation completed successfully");
}
In the above example, we have an action method called LongRunningOperation that takes a CancellationToken as a parameter. Inside the method, we first check if cancellation has been requested using the IsCancellationRequested property of the CancellationToken. If cancellation has been requested, we return a status code of 400 along with a message indicating that the operation was cancelled by the user.
If cancellation has not been requested, we proceed with the long-running operation, which in this case is simulated using the Task.Delay method. Finally, we return a success status code along with a message indicating that the operation completed successfully.
Triggering Cancellation
Now that we have a method that can handle cancellation requests, let's see how we can trigger a cancellation from the client side. One way to do this is by using the CancellationTokenSource class.
private CancellationTokenSource cancellationTokenSource;
public IActionResult StartLongRunningOperation()
{
// Create a new CancellationTokenSource
cancellationTokenSource = new CancellationTokenSource();
// Start the long-running operation
var task = LongRunningOperation(cancellationTokenSource.Token);
// Return a response indicating that the operation has started
return Ok("Operation started");
}
public IActionResult CancelLongRunningOperation()
{
// Check if a CancellationTokenSource exists
if (cancellationTokenSource != null)
{
// Cancel the operation
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
cancellationTokenSource = null;
// Return a response indicating that the operation has been cancelled
return Ok("Operation cancelled");
}
// Return a response indicating that no operation is currently running
return Ok("No operation running");
}
In the above example, we have two action methods: StartLongRunningOperation and CancelLongRunningOperation. The StartLongRunningOperation method creates a new CancellationTokenSource and starts the long-running operation by calling the LongRunningOperation method with the CancellationToken from the CancellationTokenSource.
The CancelLongRunningOperation method checks if a CancellationTokenSource exists and cancels the operation by calling the Cancel method of the CancellationTokenSource. It also disposes of the CancellationTokenSource and sets it to null. If no operation is currently running, it returns a response indicating that no operation is running.
Conclusion
In this article, we have explored how to use the CancellationToken in ASP.NET controllers to handle cancellation requests. We have seen how to check if cancellation has been requested and how to trigger a cancellation from the client side. By using the CancellationToken, you can provide a better user experience by allowing users to cancel long-running operations when needed.