Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/6674ae30974f478a4b7f to your computer and use it in GitHub Desktop.
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.
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