using System.Collections.Concurrent; namespace Chronos.App.Tests.Uploader; /// Runs async test code on one thread, as the UI dispatcher does for the upload engine. internal sealed class SingleThreadedContext : SynchronizationContext { private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; public override void Post(SendOrPostCallback d, object? state) { try { _queue.Add((d, state)); } catch (InvalidOperationException) { // Late progress reports after the test body finished are dropped. } } public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException(); public static void Run(Func body) { var previous = Current; var context = new SingleThreadedContext(); SetSynchronizationContext(context); try { var task = body(); task.ContinueWith(_ => context._queue.CompleteAdding(), TaskScheduler.Default); foreach (var (callback, state) in context._queue.GetConsumingEnumerable()) callback(state); task.GetAwaiter().GetResult(); } finally { SetSynchronizationContext(previous); } } }