public static async Task CancelANonCancellableTaskAsync(this AsyncMockService asyncMock) { Console.WriteLine(nameof(CancelANonCancellableTaskAsync)); using var cancellationTokenSource = new CancellationTokenSource(); // Listening to key press to cancel var keyBoardTask = Task.Run(() => { Console.WriteLine("Press enter to cancel"); Console.ReadKey(); // Sending the cancellation message cancellationTokenSource.Cancel(); }); try { // Running the long running task var longRunningTask = asyncMock.LongRunningOperationWithCancellationTokenAsync(100, cancellationTokenSource.Token).ConfigureAwait(false); var result = await longRunningTask; Console.WriteLine("Result {0}", result); Console.WriteLine("Press enter to continue"); } catch (TaskCanceledException) { Console.WriteLine("Task was cancelled"); } await keyBoardTask; }
public async Task LongRunningOperationWithCancellationTokenAsync_StateUnderTest_ExpectedBehavior() { // Arrange var asyncMock = new AsyncMockService(); int loop = 10; CancellationToken cancellationToken = default(global::System.Threading.CancellationToken); // Act var result = await asyncMock.LongRunningOperationWithCancellationTokenAsync( loop, cancellationToken); // Assert Assert.IsNotNull(result); Assert.AreEqual(result, 45); }