diff --git a/src/RestSharp/AsyncHelpers.cs b/src/RestSharp/AsyncHelpers.cs index 5d3db9db4..bbd0966fe 100644 --- a/src/RestSharp/AsyncHelpers.cs +++ b/src/RestSharp/AsyncHelpers.cs @@ -25,16 +25,9 @@ static class AsyncHelpers { /// /// Callback for asynchronous task to run static void RunSync(Func task) { - var currentContext = SynchronizationContext.Current; var customContext = new CustomSynchronizationContext(task); - try { - SynchronizationContext.SetSynchronizationContext(customContext); - customContext.Run(); - } - finally { - SynchronizationContext.SetSynchronizationContext(currentContext); - } + customContext.Run(); } /// @@ -80,26 +73,39 @@ public override void Post(SendOrPostCallback function, object? state) { /// Enqueues the function to be executed and executes all resulting continuations until it is completely done /// public void Run() { - Post(PostCallback, null); + var currentContext = SynchronizationContext.Current; + + try { + SynchronizationContext.SetSynchronizationContext(this); + + Post(PostCallback, null); - while (!_done) { - if (_items.TryDequeue(out var task)) { - task.Item1(task.Item2); - if (_caughtException == null) { - continue; + while (!_done) { + if (_items.TryDequeue(out var task)) { + task.Item1(task.Item2); + if (_caughtException == null) { + continue; + } + _caughtException.Throw(); + } + else { + _workItemsWaiting.WaitOne(); } - _caughtException.Throw(); - } - else { - _workItemsWaiting.WaitOne(); } } + finally { + SynchronizationContext.SetSynchronizationContext(currentContext); + } + return; + // This method is only called from within this custom context before the loop above. async void PostCallback(object? _) { try { - await _task().ConfigureAwait(false); + // Do not call ConfigureAwait(false) here to ensure all continuations are + // queued on this context, not the threadpool. + await _task(); } catch (Exception exception) { _caughtException = ExceptionDispatchInfo.Capture(exception);