Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 25 additions & 19 deletions src/RestSharp/AsyncHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,9 @@ static class AsyncHelpers {
/// </summary>
/// <param name="task">Callback for asynchronous task to run</param>
static void RunSync(Func<Task> task) {
var currentContext = SynchronizationContext.Current;
var customContext = new CustomSynchronizationContext(task);

try {
SynchronizationContext.SetSynchronizationContext(customContext);
customContext.Run();
}
finally {
SynchronizationContext.SetSynchronizationContext(currentContext);
}
customContext.Run();
}

/// <summary>
Expand Down Expand Up @@ -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
/// </summary>
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);
Expand Down