Async/Await easy cancellation in c#

Ali Alp
2 min readApr 13, 2019

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

Usage

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

private async Task ATask() { await Task.Delay(10000000); }

In order for the task to get canceled after 2 seconds

await ATask().CancelAfter(2000);

Test it

[TestFixture]
public class TaskCancellationTest
{
private async Task ATask()
{
await Task.Delay(10000000);
}

private async Task<bool> ATaskT()
{
await Task.Delay(10000000);
return true;
}

[Test]
public void TaskMilliseconds()
{
Assert.ThrowsAsync<OperationCanceledException>(
async () => { await ATask().CancelAfter(2000); });
}


[Test]
public void TaskMillisecondsT()
{
Assert.ThrowsAsync<OperationCanceledException>(
async () => { await ATaskT().CancelAfter(2000); });
}



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


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

}

Happy coding :)

dev.to is a community of over 125,000 developers writing blog posts just like this one to help us all level up. Sign Up Now
(open source and free forever ❤️)

Originally published at dev.to.

--

--

Ali Alp

“Take it easy” is nonsense , take it as hard as you can and don’t let it go :)