Search code examples
c#asynchronoustaskcancellation

Using await Task.Delay() with Cancellation token to time out a method


I am looking at a method that is structured like the code below. What is the effect of the cancellation token? Is it so that if the calculation takes longer than 1 second it won't return a T and it throws an error?

public async Task<T> doSomething(CancellationToken ct = default(CancellationToken)) {
    await Task.Delay(1000, ct);

    //do something to calculate someT that might take a while

    return someT;
}

Solution

  • A cancellation token as the name suggests is something that allows the asynchronous/parallel code to be cancelled. Consider the scenario of a user cancelling a long running process.

    In your code, the dosomething method accepts a CancellationToken which it can use to determine whether or not to cancel execution early. There are various ways to do that. First you can call ct.ThrowIfCancellationRequested() on the ct variable which as the name suggests will throw an exception you can handle in the calling code if the operation is cancelled. You can also check if(ct.IsCancellationRequested) in a loop to see if it has been and then exit out of your method.

    By passing it on to Task.Delay(1000, ct); you are giving Task.Delay a means of telling whether or not to continue waiting should a cancellation be requested before the time out has been reached.

    I may be mistaken but it also seems you aren't sure as to the purpose of Task.Delay(); it is a means to stop execution on that line for a second before proceeding. The token gives it a way to exit early should the operation be cancelled as I mentioned earlier.