DEV Community

Cover image for Async/Await easy cancellation in c#
Ali Alp
Ali Alp

Posted on • Updated on

Async/Await easy cancellation in c#

Using async/await is so fun but in the same time there are plenty of situations which the awaiting part can stuck forever, specially when there is any involvement of programming over the network. Other than that there are situations which the app must not wait more than a timeout for a response.

Therefore, the ability to set a timeout for a asynchronous operation is a must, by using CancellationToken one can achieve this and this post will demonstrate an easier method of using these CancellationTokens by applying an extension method for the Task object type.

Implementation

NuGet Installation

.Net CLI
dotnet add package easyAsyncCancel

Package Manager
Install-Package easyAsyncCancel

Enter fullscreen mode Exit fullscreen mode

Usage

Let's say there is a Task which it can take unknown amount of time to finish

private async Task Task_NetworkBound()
{
    await new HttpClient().GetStringAsync("https://dotnetfoundation.org");
}
Enter fullscreen mode Exit fullscreen mode

In order for the task to get canceled after 1 seconds

await Task_NetworkBound().CancelAfter(1000);
OR
await Task_NetworkBound().CancelAfter(1000,"Custom OperationCanceledException message");
Enter fullscreen mode Exit fullscreen mode

Test it

[TestFixture]
public class TaskCancellationTest
{
    private async Task Task_NetworkBound()
    {
        await new HttpClient().GetStringAsync("https://dotnetfoundation.org");
    }

    private async Task<string> Task_NetworkBound_T()
    {
        return await new HttpClient().GetStringAsync("https://dotnetfoundation.org");
    }

    [Test]
    public void Test_CancelWithMilliseconds()
    {
        Assert.ThrowsAsync<OperationCanceledException>(
            async () => { await Task_NetworkBound().CancelAfter(1000); });

        Assert.ThrowsAsync<OperationCanceledException>(
            async () => { await Task_NetworkBound_T().CancelAfter(1000); });
    }


    [Test]
    public void Test_CancelWithToken()
    {
        Assert.ThrowsAsync<OperationCanceledException>(async () =>
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(1000);
            await Task_NetworkBound().CancelAfter(cts.Token);
        });


        Assert.ThrowsAsync<OperationCanceledException>(async () =>
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(1000);
            await Task_NetworkBound_T().CancelAfter(cts.Token);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Full source code here

Happy coding :)

Top comments (6)

Collapse
 
gonyoda profile image
John Gonyo

A word of caution. This only cancels the await, it does not cancel the running task. Any additional code inside the awaited task will continue to execute.

Instead, you should add and pass a cancellation token to the awaited method so that the task itself is also cancelled.

That is, Task.Delay (and almost all other awaitable methods) accept(s) a cancellation token to cancel the delay before the time out expires.

Collapse
 
alialp profile image
Ali Alp

thanks bro :) Very important point you have mentioned
I have updated the post to be more clear about the IO bound operations.
good examples will be web requests or waiting on TcpClient stream and ...

Collapse
 
turnerj profile image
James Turner

That's pretty cool!

Collapse
 
vekzdran profile image
Vedran Mandić

Really really neat! Thanks and will give a try out!

Collapse
 
alialp profile image
Ali Alp

Thanks bro :)

Collapse
 
alialp profile image
Ali Alp

I have added a NuGet package for more easier usage

.Net CLI
dotnet add package easyAsyncCancel

Package Manager
Install-Package easyAsyncCancel

Happy coding :)