Created
December 11, 2020 14:36
-
-
Save KevM/d8ab95cf0f3e8f5dfc5872af17b02c30 to your computer and use it in GitHub Desktop.
exception_in_one_task_should_not_affect_others
This file contains hidden or 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
public class Experiment | |
{ | |
private readonly ITestOutputHelper _outputHelper; | |
public Experiment(ITestOutputHelper outputHelper) | |
{ | |
_outputHelper = outputHelper; | |
} | |
[Fact] | |
public async Task exception_in_one_task_should_not_affect_others() | |
{ | |
var task1 = Fast(); | |
var task2 = Fast(); | |
var task3 = Slow(); | |
var task4 = Fast(); | |
var task5 = Slow(); | |
var task6 = Error(200); | |
var task7 = Fast(); | |
var tasks = new[] { task1, task2, task3, task4, task5, task6, task7 }; | |
try | |
{ | |
await Task.WhenAll(tasks); | |
} | |
catch (Exception e) | |
{ | |
var now = DateTime.UtcNow.Ticks; | |
_outputHelper.WriteLine($"Done at: {now}\nException: {e.Message}"); | |
var successfullyCompletedTasks = tasks.Where(x => !x.IsFaulted).Where(x => x.GetAwaiter().IsCompleted); | |
var completedTaskCount = successfullyCompletedTasks.Count(); | |
completedTaskCount.Should().Be(tasks.Length - 1, "expecting all non-faulted tasks to complete"); | |
var tasksCompletedAt = successfullyCompletedTasks.Select(x => x.Result); | |
now.Should().BeGreaterThan(tasksCompletedAt.Select(x => x.Ticks).Max(), "completed tasks should be done before the catch started"); | |
Action shouldThrow = () => tasks.Where(x => x.IsFaulted).Single().GetAwaiter().GetResult(); | |
shouldThrow.Should().Throw<Exception>("failed task result throws its exception").WithMessage("Error! Error!"); | |
} | |
} | |
private async Task<DateTime> Error(int errorInMs = 500) | |
{ | |
await Task.Delay(errorInMs); | |
throw new Exception("Error! Error!"); | |
} | |
private async Task<DateTime> Fast(int endInMs = 100) | |
{ | |
await Task.Delay(endInMs); | |
return DateTime.UtcNow; | |
} | |
private async Task<DateTime> Slow(int endInMs = 3000) | |
{ | |
await Task.Delay(endInMs); | |
return DateTime.UtcNow; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment