Last active
April 11, 2023 19:59
-
-
Save StephenCleary/dfd2a8b0a50ea3040695 to your computer and use it in GitHub Desktop.
Await can just catch OperationCanceledException, regardless of how the cancellation was done.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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