-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Added back all missing Async API functions #1800
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alexeyzimarev
merged 1 commit into
restsharp:dev
from
kendallb:feature/restore-sync-functions
Apr 4, 2022
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
// Copyright © 2009-2021 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
// Adapted from Rebus | ||
|
||
using System.Collections.Concurrent; | ||
using System.Runtime.ExceptionServices; | ||
|
||
namespace RestSharp.Extensions { | ||
public static class AsyncHelpers { | ||
/// <summary> | ||
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations | ||
/// </summary> | ||
/// <param name="task">Callback for asynchronous task to run</param> | ||
public 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); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations | ||
/// </summary> | ||
/// <param name="task">Callback for asynchronous task to run</param> | ||
/// <typeparam name="T">Return type for the task</typeparam> | ||
/// <returns>Return value from the task</returns> | ||
public static T RunSync<T>(Func<Task<T>> task) { | ||
T result = default!; | ||
RunSync(async () => { result = await task(); }); | ||
return result; | ||
} | ||
|
||
/// <summary> | ||
/// Synchronization context that can be "pumped" in order to have it execute continuations posted back to it | ||
/// </summary> | ||
class CustomSynchronizationContext : SynchronizationContext { | ||
readonly ConcurrentQueue<Tuple<SendOrPostCallback, object?>> _items = new(); | ||
readonly AutoResetEvent _workItemsWaiting = new(false); | ||
readonly Func<Task> _task; | ||
ExceptionDispatchInfo? _caughtException; | ||
bool _done; | ||
|
||
/// <summary> | ||
/// Constructor for the custom context | ||
/// </summary> | ||
/// <param name="task">Task to execute</param> | ||
public CustomSynchronizationContext(Func<Task> task) => | ||
_task = task ?? throw new ArgumentNullException(nameof(task), "Please remember to pass a Task to be executed"); | ||
|
||
/// <summary> | ||
/// When overridden in a derived class, dispatches an asynchronous message to a synchronization context. | ||
/// </summary> | ||
/// <param name="function">Callback function</param> | ||
/// <param name="state">Callback state</param> | ||
public override void Post(SendOrPostCallback function, object? state) { | ||
_items.Enqueue(Tuple.Create(function, state)); | ||
_workItemsWaiting.Set(); | ||
} | ||
|
||
/// <summary> | ||
/// Enqueues the function to be executed and executes all resulting continuations until it is completely done | ||
/// </summary> | ||
public void Run() { | ||
async void PostCallback(object? _) { | ||
try { | ||
await _task().ConfigureAwait(false); | ||
} | ||
catch (Exception exception) { | ||
_caughtException = ExceptionDispatchInfo.Capture(exception); | ||
throw; | ||
} | ||
finally { | ||
Post(_ => _done = true, null); | ||
} | ||
} | ||
|
||
Post(PostCallback, null); | ||
|
||
while (!_done) { | ||
if (_items.TryDequeue(out var task)) { | ||
task.Item1(task.Item2); | ||
if (_caughtException == null) { | ||
continue; | ||
} | ||
_caughtException.Throw(); | ||
} | ||
else { | ||
_workItemsWaiting.WaitOne(); | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// When overridden in a derived class, dispatches a synchronous message to a synchronization context. | ||
/// </summary> | ||
/// <param name="function">Callback function</param> | ||
/// <param name="state">Callback state</param> | ||
public override void Send(SendOrPostCallback function, object? state) => throw new NotSupportedException("Cannot send to same thread"); | ||
|
||
/// <summary> | ||
/// When overridden in a derived class, creates a copy of the synchronization context. Not needed, so just return ourselves. | ||
/// </summary> | ||
/// <returns>Copy of the context</returns> | ||
public override SynchronizationContext CreateCopy() => this; | ||
} | ||
} | ||
} |
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
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need it here, or can it be an extension?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems simple enough to put it there, but it could be moved to RestClientExtensions I suppose? What would you prefer?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The question is if it should be a part of the potentially returned
IRestClient
interface. Do you think it makes sense to keep non-async methods as the core functionality?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, I think they should be part of the core functionality and if there was an IRestClient interface, it should include the non-async functions as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There could be two interfaces, one for sync and one for non to keep it clean, but IRestClient should inherit both as many people will use both sync and async in their code.