Skip to content

Commit 39e089f

Browse files
David EllingsworthDavid Ellingsworth
authored andcommitted
The CustomSyncrhonizationContext is designed to run a single task.
As such, the Run method should never be called more than once. Make the constructor and Run method private and add a public static Run method to run a single task on an instance of the context.
1 parent 511ce62 commit 39e089f

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/RestSharp/AsyncHelpers.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ static class AsyncHelpers {
2525
/// </summary>
2626
/// <param name="task">Callback for asynchronous task to run</param>
2727
static void RunSync(Func<Task> task) {
28-
var customContext = new CustomSynchronizationContext(task);
29-
30-
customContext.Run();
28+
CustomSynchronizationContext.Run(task);
3129
}
3230

3331
/// <summary>
@@ -56,7 +54,7 @@ class CustomSynchronizationContext : SynchronizationContext {
5654
/// Constructor for the custom context
5755
/// </summary>
5856
/// <param name="task">Task to execute</param>
59-
public CustomSynchronizationContext(Func<Task> task) =>
57+
private CustomSynchronizationContext(Func<Task> task) =>
6058
_task = task ?? throw new ArgumentNullException(nameof(task), "Please remember to pass a Task to be executed");
6159

6260
/// <summary>
@@ -72,7 +70,7 @@ public override void Post(SendOrPostCallback function, object? state) {
7270
/// <summary>
7371
/// Enqueues the function to be executed and executes all resulting continuations until it is completely done
7472
/// </summary>
75-
public void Run() {
73+
private void Run() {
7674
var currentContext = SynchronizationContext.Current;
7775

7876
try {
@@ -117,6 +115,12 @@ async void PostCallback(object? _) {
117115
}
118116
}
119117

118+
public static void Run(Func<Task> task) {
119+
var customContext = new CustomSynchronizationContext(task);
120+
121+
customContext.Run();
122+
}
123+
120124
/// <summary>
121125
/// When overridden in a derived class, dispatches a synchronous message to a synchronization context.
122126
/// </summary>

0 commit comments

Comments
 (0)