From d637e05228f2ac21b5d857d8bb6d0ef9e53bfaa5 Mon Sep 17 00:00:00 2001 From: Vladimir Pecanac Date: Fri, 13 Nov 2026 14:31:58 +0100 Subject: [PATCH] MultipleTasksDemo: move to .NET 11, add Task.WhenAll list and Task.WhenEach examples Retarget all four projects to net11.0. Replace Swashbuckle with Microsoft.AspNetCore.OpenApi, update BenchmarkDotNet to 0.15.8 with [InProcess], NUnit 5, Moq 4.21.0 and the test SDK. Fix the TaskExtensions console line, pick the client demo from the first argument, add ExecuteInParallelUsingTaskWhenAll, ExecuteUsingTaskWhenAll and ExecuteUsingTaskWhenEach with tests, and point the two parallel loop tests at the methods they name. --- .../Controllers/EmployeeController.cs | 7 +- .../MultipleTasksDemo.Api.csproj | 4 +- .../MultipleTasksDemo.Api/Program.cs | 10 +- .../Properties/launchSettings.json | 19 +- .../MultipleApiExecutorBenchmark.cs | 39 ++-- .../MultipleTasksDemo.Benchmark.csproj | 4 +- .../MultipleTasksDemo.Benchmark/Program.cs | 4 +- .../SameApiExecutorBenchmark.cs | 61 ++--- .../MultipleTasksDemo.Client/Executor.cs | 81 ++++--- .../Extensions/TaskExtensions.cs | 8 +- .../MultipleTasksDemo.Client.csproj | 2 +- .../MultipleTasksDemo.Client/Program.cs | 53 ++--- .../MultipleTasksDemo/Tests/ExecutorTests.cs | 220 ++++++++++-------- .../Tests/TaksExtensionsTests.cs | 125 ++++------ .../MultipleTasksDemo/Tests/Tests.csproj | 15 +- 15 files changed, 318 insertions(+), 334 deletions(-) diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Controllers/EmployeeController.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Controllers/EmployeeController.cs index bdf0f86e31..b9d00180b7 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Controllers/EmployeeController.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Controllers/EmployeeController.cs @@ -6,8 +6,6 @@ namespace MultipleTasksDemo.Api.Controllers; [ApiController] public class EmployeeController : ControllerBase { - private readonly Random _random = new Random(); - [HttpGet("details/{id}")] public async Task GetEmployeeDetails(Guid id) { @@ -15,7 +13,7 @@ public async Task GetEmployeeDetails(Guid id) { Id = id, Name = $"Sam_{id}", - DateOfBirth = DateTime.Now.AddYears(-1 * _random.Next(20, 30)).Date, + DateOfBirth = DateTime.Now.AddYears(-1 * Random.Shared.Next(20, 30)).Date, Address = "Employee Dummy Address" })); } @@ -33,11 +31,10 @@ public async Task GetEmployeeSalary(Guid id) [HttpGet("rating/{id}")] public async Task GetEmployeeRating(Guid id) { - return await Task.FromResult(Ok(new { Id = id, Rating = 4 })); } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/MultipleTasksDemo.Api.csproj b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/MultipleTasksDemo.Api.csproj index 60bf9ead83..424b588a67 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/MultipleTasksDemo.Api.csproj +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/MultipleTasksDemo.Api.csproj @@ -1,13 +1,13 @@ - net6.0 + net11.0 enable enable - + diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Program.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Program.cs index 48863a6d6c..ef8b1e79d2 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Program.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Program.cs @@ -1,19 +1,13 @@ var builder = WebApplication.CreateBuilder(args); -// Add services to the container. - builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +builder.Services.AddOpenApi(); var app = builder.Build(); -// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { - app.UseSwagger(); - app.UseSwaggerUI(); + app.MapOpenApi(); } app.UseHttpsRedirection(); diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Properties/launchSettings.json b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Properties/launchSettings.json index 27923ffa91..c54dcab7d5 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Properties/launchSettings.json +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Api/Properties/launchSettings.json @@ -1,31 +1,14 @@ { "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:32300", - "sslPort": 44347 - } - }, "profiles": { "MultipleTasksDemo.Api": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", + "launchBrowser": false, "applicationUrl": "https://localhost:7145;http://localhost:5145", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } } } } diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleApiExecutorBenchmark.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleApiExecutorBenchmark.cs index 2ce98760f2..28752d4bf0 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleApiExecutorBenchmark.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleApiExecutorBenchmark.cs @@ -1,26 +1,27 @@ using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; using MultipleTasksDemo.Client; -namespace MultipleTasksDemo.Benchmark +namespace MultipleTasksDemo.Benchmark; + +[InProcess] +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public class MultipleApiExecutorBenchmark { - [MemoryDiagnoser] - [Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)] - [RankColumn] - public class MultipleApiExecutorBenchmark - { - private Executor _executor = new(new EmployeeApiFacade()); - private readonly Guid _id = new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"); + private readonly Executor _executor = new(new EmployeeApiFacade()); + private readonly Guid _id = new("7119e779-3054-493c-8cf7-c617b4aa0f4e"); - [Benchmark(Baseline = true)] - public async Task ExecuteInSequence() - { - await _executor.ExecuteInSequence(_id); - } + [Benchmark(Baseline = true)] + public async Task ExecuteInSequence() + { + return await _executor.ExecuteInSequence(_id); + } - [Benchmark] - public async Task ExecuteInParallel() - { - await _executor.ExecuteInParallel(_id); - } + [Benchmark] + public async Task ExecuteInParallel() + { + return await _executor.ExecuteInParallel(_id); } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleTasksDemo.Benchmark.csproj b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleTasksDemo.Benchmark.csproj index f189067ea7..5bcfcf01e5 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleTasksDemo.Benchmark.csproj +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/MultipleTasksDemo.Benchmark.csproj @@ -2,13 +2,13 @@ Exe - net6.0 + net11.0 enable enable - + diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/Program.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/Program.cs index e8656f8a4f..de11df47dc 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/Program.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/Program.cs @@ -1,6 +1,4 @@ using BenchmarkDotNet.Running; using MultipleTasksDemo.Benchmark; -//BenchmarkRunner.Run(); - -BenchmarkRunner.Run(); +BenchmarkSwitcher.FromAssembly(typeof(MultipleApiExecutorBenchmark).Assembly).Run(args); diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/SameApiExecutorBenchmark.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/SameApiExecutorBenchmark.cs index 46da9718fe..4a9e3f2a7b 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/SameApiExecutorBenchmark.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Benchmark/SameApiExecutorBenchmark.cs @@ -1,37 +1,44 @@ using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Order; using MultipleTasksDemo.Client; -namespace MultipleTasksDemo.Benchmark +namespace MultipleTasksDemo.Benchmark; + +[InProcess] +[MemoryDiagnoser] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +public class SameApiExecutorBenchmark { - [MemoryDiagnoser] - [Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)] - [RankColumn] - public class SameApiExecutorBenchmark + private readonly Executor _executor = new(new EmployeeApiFacade()); + private readonly Guid[] _employeeIds = + [ + new("7119e779-3054-493c-8cf7-c617b4aa0f4e"), + new("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), + new("165bcfa8-3a4f-4850-a681-bc496616f830") + ]; + + [Benchmark(Baseline = true)] + public async Task ExecuteUsingNormalForEach() { - private Executor _executor = new(new EmployeeApiFacade()); - private readonly Guid[] _employeeIds = new[] - { - new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), - new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), - new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") - }; + await _executor.ExecuteUsingNormalForEach(_employeeIds); + } - [Benchmark(Baseline = true)] - public async Task ExecuteUsingNormalForEach() - { - await _executor.ExecuteUsingNormalForEach(_employeeIds); - } + [Benchmark] + public void ExecuteUsingParallelForeach() + { + _executor.ExecuteUsingParallelForeach(_employeeIds); + } - [Benchmark] - public void ExecuteUsingParallelForeach() - { - _executor.ExecuteUsingParallelForeach(_employeeIds); - } + [Benchmark] + public async Task ExecuteUsingParallelForeachAsync() + { + await _executor.ExecuteUsingParallelForeachAsync(_employeeIds); + } - [Benchmark] - public async Task ExecuteUsingParallelForeachAsync() - { - await _executor.ExecuteUsingParallelForeachAsync(_employeeIds); - } + [Benchmark] + public async Task ExecuteUsingTaskWhenAll() + { + await _executor.ExecuteUsingTaskWhenAll(_employeeIds); } } diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Executor.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Executor.cs index 5db9bb1269..84031fd808 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Executor.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Executor.cs @@ -1,55 +1,59 @@ using System.Collections.Concurrent; -using System.Diagnostics; using MultipleTasksDemo.Client.Contracts; using TaskExtensions = MultipleTasksDemo.Client.Extensions.TaskExtensions; namespace MultipleTasksDemo.Client; -public class Executor +public class Executor(IEmployeeApiFacade employeeApiFacade) { - private readonly IEmployeeApiFacade _employeeApiFacade; - - public Executor(IEmployeeApiFacade employeeApiFacade) - { - _employeeApiFacade = employeeApiFacade; - } + private readonly IEmployeeApiFacade _employeeApiFacade = employeeApiFacade; public async Task ExecuteInSequence(Guid id) - { + { var employeeDetails = await _employeeApiFacade.GetEmployeeDetails(id); var employeeSalary = await _employeeApiFacade.GetEmployeeSalary(id); - var employeeRating = await _employeeApiFacade.GetEmployeeRating(id); + var employeeRating = await _employeeApiFacade.GetEmployeeRating(id); return new EmployeeProfile(employeeDetails, employeeSalary, employeeRating); } - public async Task ExecuteInParallel(Guid id) - { + public async Task ExecuteInParallelUsingTaskWhenAll(Guid id) + { var employeeDetailsTask = _employeeApiFacade.GetEmployeeDetails(id); var employeeSalaryTask = _employeeApiFacade.GetEmployeeSalary(id); var employeeRatingTask = _employeeApiFacade.GetEmployeeRating(id); - //await Task.WhenAll(employeeDetailsTask, employeeSalaryTask, employeeRatingTask); + await Task.WhenAll(employeeDetailsTask, employeeSalaryTask, employeeRatingTask); - //var employeeDetails = await employeeDetailsTask; - //var employeeSalary = await employeeSalaryTask; - //var employeeRating = await employeeRatingTask; + var employeeDetails = await employeeDetailsTask; + var employeeSalary = await employeeSalaryTask; + var employeeRating = await employeeRatingTask; + + return new EmployeeProfile(employeeDetails, employeeSalary, employeeRating); + } + + public async Task ExecuteInParallel(Guid id) + { + var employeeDetailsTask = _employeeApiFacade.GetEmployeeDetails(id); + var employeeSalaryTask = _employeeApiFacade.GetEmployeeSalary(id); + var employeeRatingTask = _employeeApiFacade.GetEmployeeRating(id); - var (employeeDetails, employeeSalary, employeeRating) = await TaskExtensions.WhenAll(employeeDetailsTask, employeeSalaryTask, employeeRatingTask); + var (employeeDetails, employeeSalary, employeeRating) + = await TaskExtensions.WhenAll(employeeDetailsTask, employeeSalaryTask, employeeRatingTask); return new EmployeeProfile(employeeDetails, employeeSalary, employeeRating); } public async Task> ExecuteUsingNormalForEach(IEnumerable employeeIds) - { - List employeeDetails = new(); - + { + List employeeDetails = []; + foreach (var id in employeeIds) { var employeeDetail = await _employeeApiFacade.GetEmployeeDetails(id); employeeDetails.Add(employeeDetail); - } + } return employeeDetails; } @@ -59,16 +63,16 @@ public IEnumerable ExecuteUsingParallelForeach(IEnumerable employeeDetails = new(); + ConcurrentBag employeeDetails = []; Parallel.ForEach(employeeIds, parallelOptions, id => { var employeeDetail = _employeeApiFacade.GetEmployeeDetails(id).GetAwaiter().GetResult(); employeeDetails.Add(employeeDetail); - }); + }); return employeeDetails; } @@ -78,17 +82,38 @@ public async Task> ExecuteUsingParallelForeachAsync ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = 3 - }; + }; - ConcurrentBag employeeDetails = new(); + ConcurrentBag employeeDetails = []; await Parallel.ForEachAsync(employeeIds, parallelOptions, async (id, _) => { var employeeDetail = await _employeeApiFacade.GetEmployeeDetails(id); employeeDetails.Add(employeeDetail); - }); + }); + + return employeeDetails; + } + + public async Task> ExecuteUsingTaskWhenAll(IEnumerable employeeIds) + { + var tasks = employeeIds.Select(id => _employeeApiFacade.GetEmployeeDetails(id)); + + return await Task.WhenAll(tasks); + } + + public async Task> ExecuteUsingTaskWhenEach(IEnumerable employeeIds) + { + var tasks = employeeIds.Select(id => _employeeApiFacade.GetEmployeeDetails(id)); + + List employeeDetails = []; + + await foreach (var task in Task.WhenEach(tasks)) + { + employeeDetails.Add(await task); + } return employeeDetails; } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Extensions/TaskExtensions.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Extensions/TaskExtensions.cs index a7dcf8b307..bb7091291c 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Extensions/TaskExtensions.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Extensions/TaskExtensions.cs @@ -9,12 +9,12 @@ public class TaskExtensions { await allTasks; } - catch (Exception exp) + catch { - Console.WriteLine("Task Exception", exp); - throw allTasks.Exception; + Console.WriteLine("Task Exception"); + throw allTasks.Exception!; } return (task1.Result, task2.Result, task3.Result); } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/MultipleTasksDemo.Client.csproj b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/MultipleTasksDemo.Client.csproj index 74abf5c976..5bf6c9b8cf 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/MultipleTasksDemo.Client.csproj +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/MultipleTasksDemo.Client.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net11.0 enable enable diff --git a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Program.cs b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Program.cs index b9c4855770..d804833892 100644 --- a/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Program.cs +++ b/async-csharp/MultipleTasksDemo/MultipleTasksDemo.Client/Program.cs @@ -4,41 +4,32 @@ Executor _executor = new(new EmployeeApiFacade()); var _id = new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"); -var _employeeIds = new[] -{ - new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), - new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), - new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") -}; +Guid[] _employeeIds = +[ + new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), + new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), + new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") +]; + +// dotnet run -- , for example: dotnet run -- parallel +var demo = args.Length > 0 ? args[0] : "sequence"; try { - await ExecuteInSequence(); - - //await ExecuteInParallel(); - - //await ExecuteUsingNormalForEach(); - - //ExecuteUsingParallelForeach(); - - //await ExecuteUsingParallelForeachAsync(); + switch (demo) + { + case "sequence": (await _executor.ExecuteInSequence(_id)).Display(); break; + case "parallel-when-all": (await _executor.ExecuteInParallelUsingTaskWhenAll(_id)).Display(); break; + case "parallel": (await _executor.ExecuteInParallel(_id)).Display(); break; + case "foreach": (await _executor.ExecuteUsingNormalForEach(_employeeIds)).Display(); break; + case "parallel-foreach": _executor.ExecuteUsingParallelForeach(_employeeIds).Display(); break; + case "parallel-foreach-async": (await _executor.ExecuteUsingParallelForeachAsync(_employeeIds)).Display(); break; + case "when-all": (await _executor.ExecuteUsingTaskWhenAll(_employeeIds)).Display(); break; + case "when-each": (await _executor.ExecuteUsingTaskWhenEach(_employeeIds)).Display(); break; + default: Console.WriteLine($"Unknown demo: {demo}"); break; + } } catch (Exception e) { - Console.WriteLine(e); + Console.WriteLine(e); } - -Console.ReadKey(); - -async Task ExecuteInSequence() - => (await _executor.ExecuteInSequence(_id)).Display(); - -async Task ExecuteInParallel() - => (await _executor.ExecuteInParallel(_id)).Display(); - -async Task ExecuteUsingNormalForEach() - => (await _executor.ExecuteUsingNormalForEach(_employeeIds!)).Display(); - -void ExecuteUsingParallelForeach() => _executor.ExecuteUsingParallelForeach(_employeeIds!).Display(); - -async Task ExecuteUsingParallelForeachAsync() => (await _executor.ExecuteUsingParallelForeachAsync(_employeeIds!)).Display(); diff --git a/async-csharp/MultipleTasksDemo/Tests/ExecutorTests.cs b/async-csharp/MultipleTasksDemo/Tests/ExecutorTests.cs index 3796f0ac72..6faa246bac 100644 --- a/async-csharp/MultipleTasksDemo/Tests/ExecutorTests.cs +++ b/async-csharp/MultipleTasksDemo/Tests/ExecutorTests.cs @@ -1,129 +1,143 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Moq; +using Moq; using MultipleTasksDemo.Client; using MultipleTasksDemo.Client.Contracts; using NUnit.Framework; -namespace Tests +namespace Tests; + +[TestFixture] +public class ExecutorTests { - [TestFixture] - public class ExecutorTests + private static readonly Guid[] EmployeeIds = + [ + new("7119e779-3054-493c-8cf7-c617b4aa0f4e"), + new("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), + new("165bcfa8-3a4f-4850-a681-bc496616f830") + ]; + + private Mock _apiFacade = null!; + private Executor _executor = null!; + + [SetUp] + public void Setup() { - private Mock _apiFacade; - private Executor _executor; + _apiFacade = new Mock(); - [SetUp] - public void Setup() - { - _apiFacade = new Mock(); - - _apiFacade.Setup(m => m.GetEmployeeDetails(It.IsAny())).ReturnsAsync((Guid id) => new EmployeeDetails - { - Id = id, - Name = "Test Name", - Address = "Test Address", - DateOfBirth = new DateTime(1980, 12, 01) - }); - _apiFacade.Setup(m => m.GetEmployeeSalary(It.IsAny())).ReturnsAsync(2000); - _apiFacade.Setup(m => m.GetEmployeeRating(It.IsAny())).ReturnsAsync(4); - - _executor = new Executor(_apiFacade.Object); - } - - [Test] - public async Task WhenExecuteInSequenceIsInvoked_ReturnsEmployeeProfileWithAllData() + _apiFacade.Setup(m => m.GetEmployeeDetails(It.IsAny())).ReturnsAsync((Guid id) => new EmployeeDetails { - var id = Guid.NewGuid(); + Id = id, + Name = "Test Name", + Address = "Test Address", + DateOfBirth = new DateTime(1980, 12, 01) + }); + _apiFacade.Setup(m => m.GetEmployeeSalary(It.IsAny())).ReturnsAsync(2000); + _apiFacade.Setup(m => m.GetEmployeeRating(It.IsAny())).ReturnsAsync(4); + + _executor = new Executor(_apiFacade.Object); + } - var employeeProfile = await _executor.ExecuteInSequence(id); + private void AssertProfile(EmployeeProfile employeeProfile, Guid id) + { + _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Once); + _apiFacade.Verify(x => x.GetEmployeeSalary(It.IsAny()), Times.Once); + _apiFacade.Verify(x => x.GetEmployeeRating(It.IsAny()), Times.Once); + Assert.That(employeeProfile.EmployeeDetails.Name, Is.EqualTo("Test Name")); + Assert.That(employeeProfile.EmployeeDetails.Address, Is.EqualTo("Test Address")); + Assert.That(employeeProfile.EmployeeDetails.DateOfBirth, Is.EqualTo(new DateTime(1980, 12, 01))); + Assert.That(employeeProfile.EmployeeDetails.Id, Is.EqualTo(id)); + Assert.That(employeeProfile.Salary, Is.EqualTo(2000)); + Assert.That(employeeProfile.Rating, Is.EqualTo(4)); + } - _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Once); - _apiFacade.Verify(x => x.GetEmployeeSalary(It.IsAny()), Times.Once); - _apiFacade.Verify(x => x.GetEmployeeRating(It.IsAny()), Times.Once); - Assert.AreEqual("Test Name", employeeProfile.EmployeeDetails.Name); - Assert.AreEqual("Test Address", employeeProfile.EmployeeDetails.Address); - Assert.AreEqual(new DateTime(1980, 12, 01), employeeProfile.EmployeeDetails.DateOfBirth); - Assert.AreEqual(id, employeeProfile.EmployeeDetails.Id); - } + private void AssertAllDetails(IEnumerable employeeDetails) + { + _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Exactly(3)); + Assert.That(employeeDetails.Select(e => e.Id), Is.EquivalentTo(EmployeeIds)); + } - [Test] - public async Task WhenExecuteInParallelIsInvoked_ReturnsEmployeeProfileWithAllData() - { - var id = Guid.NewGuid(); + [Test] + public async Task WhenExecuteInSequenceIsInvoked_ReturnsEmployeeProfileWithAllData() + { + var id = Guid.NewGuid(); - var employeeProfile = await _executor.ExecuteInParallel(id); + AssertProfile(await _executor.ExecuteInSequence(id), id); + } - _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Once); - _apiFacade.Verify(x => x.GetEmployeeSalary(It.IsAny()), Times.Once); - _apiFacade.Verify(x => x.GetEmployeeRating(It.IsAny()), Times.Once); - Assert.AreEqual("Test Name", employeeProfile.EmployeeDetails.Name); - Assert.AreEqual("Test Address", employeeProfile.EmployeeDetails.Address); - Assert.AreEqual(new DateTime(1980, 12, 01), employeeProfile.EmployeeDetails.DateOfBirth); - Assert.AreEqual(id, employeeProfile.EmployeeDetails.Id); - } + [Test] + public async Task WhenExecuteInParallelUsingTaskWhenAllIsInvoked_ReturnsEmployeeProfileWithAllData() + { + var id = Guid.NewGuid(); - [Test] - public async Task WhenExceptinIsThrownFromApiFacadeForExecuteInParallel_AggregateExceptionisThrown() - { - _apiFacade.Setup(m => m.GetEmployeeDetails(It.IsAny())).ThrowsAsync(new Exception("Test Exception 1")); - _apiFacade.Setup(m => m.GetEmployeeSalary(It.IsAny())).ThrowsAsync(new Exception("Test Exception 2")); + AssertProfile(await _executor.ExecuteInParallelUsingTaskWhenAll(id), id); + } + + [Test] + public async Task WhenExecuteInParallelIsInvoked_ReturnsEmployeeProfileWithAllData() + { + var id = Guid.NewGuid(); - var aggregateException = Assert.ThrowsAsync(async () => await _executor.ExecuteInParallel(Guid.NewGuid())); + AssertProfile(await _executor.ExecuteInParallel(id), id); + } - Assert.AreEqual(2, aggregateException?.InnerExceptions.Count); - Assert.AreEqual("Test Exception 1", aggregateException?.InnerExceptions[0].Message); - Assert.AreEqual("Test Exception 2", aggregateException?.InnerExceptions[1].Message); + [Test] + public async Task WhenExceptionIsThrownFromApiFacadeForExecuteInParallel_AggregateExceptionIsThrown() + { + _apiFacade.Setup(m => m.GetEmployeeDetails(It.IsAny())).ThrowsAsync(new Exception("Test Exception 1")); + _apiFacade.Setup(m => m.GetEmployeeSalary(It.IsAny())).ThrowsAsync(new Exception("Test Exception 2")); - } + var aggregateException = await Assert.ThrowsAsync( + async () => await _executor.ExecuteInParallel(Guid.NewGuid())); - [Test] - public async Task WhenExecuteUsingNormalForEachIsInvoked_ReturnsCollectionOfEmployeeDetails() - { - var employeeIds = new[] - { - new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), - new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), - new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") - }; + Assert.That(aggregateException!.InnerExceptions, Has.Count.EqualTo(2)); + Assert.That(aggregateException.InnerExceptions[0].Message, Is.EqualTo("Test Exception 1")); + Assert.That(aggregateException.InnerExceptions[1].Message, Is.EqualTo("Test Exception 2")); + } - var employeeDetails = await _executor.ExecuteUsingNormalForEach(employeeIds); + [Test] + public async Task WhenExecuteUsingNormalForEachIsInvoked_ReturnsCollectionOfEmployeeDetails() + { + AssertAllDetails(await _executor.ExecuteUsingNormalForEach(EmployeeIds)); + } - _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Exactly(3)); - Assert.AreEqual(3, employeeDetails.ToList().Count); - } + [Test] + public void WhenExecuteUsingParallelForeachIsInvoked_ReturnsCollectionOfEmployeeDetails() + { + AssertAllDetails(_executor.ExecuteUsingParallelForeach(EmployeeIds)); + } - [Test] - public async Task WhenExecuteUsingParallelForeachIsInvoked_ReturnsCollectionOfEmployeeDetails() - { - var employeeIds = new[] - { - new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), - new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), - new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") - }; + [Test] + public async Task WhenExecuteUsingParallelForeachAsyncIsInvoked_ReturnsCollectionOfEmployeeDetails() + { + AssertAllDetails(await _executor.ExecuteUsingParallelForeachAsync(EmployeeIds)); + } - var employeeDetails = await _executor.ExecuteUsingNormalForEach(employeeIds); + [Test] + public async Task WhenExecuteUsingTaskWhenAllIsInvoked_ReturnsDetailsInInputOrder() + { + var employeeDetails = await _executor.ExecuteUsingTaskWhenAll(EmployeeIds); - _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Exactly(3)); - Assert.AreEqual(3, employeeDetails.ToList().Count); - } + _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Exactly(3)); + Assert.That(employeeDetails.Select(e => e.Id), Is.EqualTo(EmployeeIds)); + } - [Test] - public async Task WhenExecuteUsingParallelForeachAsyncIsInvoked_ReturnsCollectionOfEmployeeDetails() + [Test] + public async Task WhenExecuteUsingTaskWhenEachIsInvoked_ReturnsDetailsInCompletionOrder() + { + // The first id answers last and the last id answers first. + var delays = new Dictionary + { + [EmployeeIds[0]] = 300, + [EmployeeIds[1]] = 150, + [EmployeeIds[2]] = 0 + }; + _apiFacade.Setup(m => m.GetEmployeeDetails(It.IsAny())).Returns(async (Guid id) => { - var employeeIds = new[] - { - new Guid("7119e779-3054-493c-8cf7-c617b4aa0f4e"), - new Guid("cbb9c89f-3718-43d9-8763-b3fa3765bcea"), - new Guid("165bcfa8-3a4f-4850-a681-bc496616f830") - }; - - var employeeDetails = await _executor.ExecuteUsingNormalForEach(employeeIds); - - _apiFacade.Verify(x => x.GetEmployeeDetails(It.IsAny()), Times.Exactly(3)); - Assert.AreEqual(3, employeeDetails.ToList().Count); - } + await Task.Delay(delays[id]); + return new EmployeeDetails { Id = id }; + }); + + var employeeDetails = await _executor.ExecuteUsingTaskWhenEach(EmployeeIds); + + Assert.That(employeeDetails.Select(e => e.Id), Is.EqualTo(EmployeeIds.Reverse())); } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/Tests/TaksExtensionsTests.cs b/async-csharp/MultipleTasksDemo/Tests/TaksExtensionsTests.cs index 7a6d202cda..5918b3755e 100644 --- a/async-csharp/MultipleTasksDemo/Tests/TaksExtensionsTests.cs +++ b/async-csharp/MultipleTasksDemo/Tests/TaksExtensionsTests.cs @@ -1,90 +1,63 @@ -using System; -using System.Threading.Tasks; using NUnit.Framework; using TaskExtensions = MultipleTasksDemo.Client.Extensions.TaskExtensions; -namespace Tests +namespace Tests; + +[TestFixture] +public class TaskExtensionsTests { - [TestFixture] - public class Tests + private static async Task Succeed(int value) { - [Test] - public void WhenAll_ThrowsAggregateException() - { - var t1 = Task.Run(async () => - { - await Task.Delay(10); - throw new Exception("Test Exception 1"); - return 1; - }); - var t2 = Task.Run(async () => - { - await Task.Delay(10); - throw new Exception("Test Exception 2"); - return 2; - }); - var t3 = Task.Run(async () => - { - await Task.Delay(10); - return 3; - }); + await Task.Delay(10); + return value; + } - Assert.ThrowsAsync(async () => { var (result1, result2, result3) = await TaskExtensions.WhenAll(t1, t2, t3); }); - } + private static async Task Fail(string message) + { + await Task.Delay(10); + throw new Exception(message); + } - [Test] - public void WhenAll_ReturnsIndividualExceptionsOnEachTask() - { - var t1 = Task.Run(async () => - { - await Task.Delay(10); - throw new Exception("Test Exception 1"); - return 1; - }); - var t2 = Task.Run(async () => - { - await Task.Delay(10); - throw new Exception("Test Exception 2"); - return 2; - }); - var t3 = Task.Run(async () => - { - await Task.Delay(10); - return 3; - }); + [Test] + public async Task WhenAll_ThrowsAggregateException() + { + await Assert.ThrowsAsync(async () => + await TaskExtensions.WhenAll(Fail("Test Exception 1"), Fail("Test Exception 2"), Succeed(3))); + } - var aggregateException = Assert.ThrowsAsync(async () => { var (result1, result2, result3) = await TaskExtensions.WhenAll(t1, t2, t3); }); + [Test] + public async Task WhenAll_ReturnsIndividualExceptionsOnEachTask() + { + var aggregateException = await Assert.ThrowsAsync(async () => + await TaskExtensions.WhenAll(Fail("Test Exception 1"), Fail("Test Exception 2"), Succeed(3))); - Assert.AreEqual(2, aggregateException?.InnerExceptions.Count); - Assert.AreEqual("Test Exception 1", aggregateException?.InnerExceptions[0].Message); - Assert.AreEqual("Test Exception 2", aggregateException?.InnerExceptions[1].Message); - } + Assert.That(aggregateException!.InnerExceptions.Select(e => e.Message), + Is.EquivalentTo(new[] { "Test Exception 1", "Test Exception 2" })); + } + + [Test] + public async Task WhenAll_ReturnsResultsForEachTask() + { + var (result1, result2, result3) = await TaskExtensions.WhenAll(Succeed(1), Succeed(2), Succeed(3)); - [Test] - public async Task WhenAll_ReturnsResultsForEachTask() - { - var t1 = Task.Run(async () => - { - await Task.Delay(10); - return 1; - }); - var t2 = Task.Run(async () => - { - await Task.Delay(10); - return 2; - }); - var t3 = Task.Run(async () => - { - await Task.Delay(10); - return 3; - }); + Assert.That(result1, Is.EqualTo(1)); + Assert.That(result2, Is.EqualTo(2)); + Assert.That(result3, Is.EqualTo(3)); + } + + [Test] + public async Task PlainTaskWhenAll_AwaitThrowsOnlyTheExceptionOfTheTaskThatFailedFirst() + { + var first = new TaskCompletionSource(); + var second = new TaskCompletionSource(); + var whenAll = Task.WhenAll(first.Task, second.Task); - var (result1, result2, result3) = await TaskExtensions.WhenAll(t1, t2, t3); + second.SetException(new Exception("Test Exception 2")); + first.SetException(new Exception("Test Exception 1")); - Assert.AreEqual(1, result1); - Assert.AreEqual(2, result2); - Assert.AreEqual(3, result3); - } + var exception = await Assert.ThrowsAsync(async () => await whenAll); + Assert.That(exception!.Message, Is.EqualTo("Test Exception 2")); + Assert.That(whenAll.Exception!.InnerExceptions, Has.Count.EqualTo(2)); } -} \ No newline at end of file +} diff --git a/async-csharp/MultipleTasksDemo/Tests/Tests.csproj b/async-csharp/MultipleTasksDemo/Tests/Tests.csproj index 910dec78fd..a7504e98c9 100644 --- a/async-csharp/MultipleTasksDemo/Tests/Tests.csproj +++ b/async-csharp/MultipleTasksDemo/Tests/Tests.csproj @@ -1,18 +1,19 @@ - net6.0 + net11.0 enable - + enable false - - - - - + + + + + +