Created
November 18, 2020 15:43
-
-
Save BanksySan/886c3c98c4b4a15e3f705d91d0f2c306 to your computer and use it in GitHub Desktop.
Examples of *CancelledException causes.
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.Diagnostics.CodeAnalysis; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Xunit; | |
namespace Junk.TaskCanceled.Tests | |
{ | |
[SuppressMessage("ReSharper", "MethodSupportsCancellation", Justification = "That's the point of the test.")] | |
public class Tests | |
{ | |
private const bool REQUEST_CANCELLATION = true; | |
private const bool DO_NOT_REQUEST_CANCELLATION = true; | |
[Theory(DisplayName = "Cases where ThreadCancelledException is thrown.")] | |
[InlineData(REQUEST_CANCELLATION)] | |
[InlineData(DO_NOT_REQUEST_CANCELLATION)] | |
public void ThrowsTaskCancelledException(bool shouldRequestCancellation) | |
{ | |
var cancellationTokenSource = new CancellationTokenSource(); | |
var cancellationToken = cancellationTokenSource.Token; | |
var task = new Task(() => TaskCases.WaitUntil(100), cancellationToken); | |
task.Start(); | |
if (shouldRequestCancellation) | |
cancellationTokenSource.Cancel(); | |
var aggregateException = Assert.Throws<AggregateException>(() => task.Wait()); | |
Assert.Equal(1, aggregateException.InnerExceptions.Count); | |
Assert.IsType<TaskCanceledException>(aggregateException.InnerExceptions[0]); | |
} | |
[Theory(DisplayName = "No exception is thrown at all.")] | |
[InlineData(0)] | |
[InlineData(100)] | |
[InlineData(500)] | |
public void NoExceptionThrown() | |
{ | |
var cancellationTokenSource = new CancellationTokenSource(); | |
var cancellationToken = cancellationTokenSource.Token; | |
var task = new Task(() => TaskCases.WaitUntil(100, cancellationToken)); | |
task.Start(); | |
cancellationTokenSource.Cancel(); | |
task.Wait(1); | |
} | |
[Theory(DisplayName = "Throws an OperationCancelledException")] | |
public void ThrowsOperationCancelledException() | |
{ | |
// TODO | |
} | |
} | |
internal static class TaskCases | |
{ | |
public static void WaitUntil(int milliseconds) | |
{ | |
Thread.Sleep(milliseconds); | |
} | |
public static void WaitUntil(int milliseconds, CancellationToken token) | |
{ | |
Thread.Sleep(milliseconds); | |
if (token.IsCancellationRequested) return; | |
throw new Exception("It wasn't cancelled!!!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment