Last active
August 29, 2015 14:16
-
-
Save StephenCleary/6674ae30974f478a4b7f to your computer and use it in GitHub Desktop.
Wait/Result can expect OperationCanceledException as its AggregateException.InnerException, 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 WaitCanTreatInnerExceptionAsOperationCanceledException | |
{ | |
[TestMethod] | |
public void CancellationTokenPassedToStartNew_CanTreatAsOperationCanceledException() | |
{ | |
var cts = new CancellationTokenSource(); | |
try | |
{ | |
cts.Cancel(); | |
Task.Factory.StartNew(() => { }, cts.Token).Wait(); | |
Assert.Fail("Wait was expected to throw."); | |
} | |
catch (AggregateException exception) | |
{ | |
var ex = (OperationCanceledException)exception.InnerException; | |
Assert.AreEqual(cts.Token, ex.CancellationToken); | |
} | |
} | |
[TestMethod] | |
public void CancellationTokenObservedByDelegate_CanTreatAsOperationCanceledException() | |
{ | |
var cts = new CancellationTokenSource(); | |
try | |
{ | |
cts.Cancel(); | |
Task.Factory.StartNew(() => { cts.Token.ThrowIfCancellationRequested(); }).Wait(); | |
Assert.Fail("Wait was expected to throw."); | |
} | |
catch (AggregateException exception) | |
{ | |
var ex = (OperationCanceledException)exception.InnerException; | |
Assert.AreEqual(cts.Token, ex.CancellationToken); | |
} | |
} | |
[TestMethod] | |
public void 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(); | |
task.Wait(); | |
Assert.Fail("Wait was expected to throw."); | |
} | |
catch (AggregateException exception) | |
{ | |
var ex = (OperationCanceledException)exception.InnerException; | |
Assert.AreEqual(cts.Token, ex.CancellationToken); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment