Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Last active April 11, 2023 19:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/dfd2a8b0a50ea3040695 to your computer and use it in GitHub Desktop.
Save StephenCleary/dfd2a8b0a50ea3040695 to your computer and use it in GitHub Desktop.
Await can just catch OperationCanceledException, regardless of how the cancellation was done.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class AwaitCanJustCatchOperationCanceledException
{
[TestMethod]
public async Task CancellationTokenPassedToStartNew_CanTreatAsOperationCanceledException()
{
var cts = new CancellationTokenSource();
try
{
cts.Cancel();
await Task.Factory.StartNew(() => { }, cts.Token);
Assert.Fail("await was expected to throw OperationCanceledException.");
}
catch (OperationCanceledException ex)
{
Assert.AreEqual(cts.Token, ex.CancellationToken);
}
}
[TestMethod]
public async Task CancellationTokenObservedByDelegate_CanTreatAsOperationCanceledException()
{
var cts = new CancellationTokenSource();
try
{
cts.Cancel();
await Task.Factory.StartNew(() => { cts.Token.ThrowIfCancellationRequested(); });
Assert.Fail("await was expected to throw OperationCanceledException.");
}
catch (OperationCanceledException ex)
{
Assert.AreEqual(cts.Token, ex.CancellationToken);
}
}
[TestMethod]
public async Task CancellationTokenObservedAndPassed_CanTreatAsOperationCanceledException()
{
var cts = new CancellationTokenSource();
try
{
var task = Task.Factory.StartNew(() => { while (true) cts.Token.ThrowIfCancellationRequested(); }, cts.Token);
while (task.Status != TaskStatus.Running)
;
cts.Cancel();
await task;
Assert.Fail("await was expected to throw OperationCanceledException.");
}
catch (OperationCanceledException ex)
{
Assert.AreEqual(cts.Token, ex.CancellationToken);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment