Skip to content
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

fix: try executing on the thread pool #3449

Merged
merged 2 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 15 additions & 27 deletions src/Paramore.Brighter/Tasks/BrighterSynchronizationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ namespace Paramore.Brighter.Tasks
/// Only uses one thread, so predictable performance, but may have many messages queued. Once queue length exceeds
/// buffer size, we will stop reading new work.
/// </remarks>
internal class BrighterSynchronizationContext : SynchronizationContext
public class BrighterSynchronizationContext : SynchronizationContext
{
private readonly ExecutionContext? _executionContext;

/// <summary>
/// Gets the synchronization helper.
/// </summary>
Expand All @@ -62,7 +60,6 @@ internal class BrighterSynchronizationContext : SynchronizationContext
public BrighterSynchronizationContext(BrighterSynchronizationHelper synchronizationHelper)
{
SynchronizationHelper = synchronizationHelper;
_executionContext = ExecutionContext.Capture();
}

/// <summary>
Expand Down Expand Up @@ -132,8 +129,7 @@ public override void Post(SendOrPostCallback callback, object? state)
Debug.IndentLevel = 0;

if (callback == null) throw new ArgumentNullException(nameof(callback));
var ctxt = ExecutionContext.Capture();
bool queued = SynchronizationHelper.Enqueue(new ContextMessage(callback, state, ctxt), true);
bool queued = SynchronizationHelper.Enqueue(new ContextMessage(callback, state), true);

if (queued) return;

Expand All @@ -143,26 +139,19 @@ public override void Post(SendOrPostCallback callback, object? state)
// If the execution context can help, we might be able to redirect; if not just run immediately on this thread

var contextCallback = new ContextCallback(callback);
if (ctxt != null && ctxt != _executionContext)
{
Debug.WriteLine(string.Empty);
Debug.IndentLevel = 1;
Debug.WriteLine($"BrighterSynchronizationContext: Post Failed to queue {callback.Method.Name} on thread {Thread.CurrentThread.ManagedThreadId}");
Debug.WriteLine($"BrighterSynchronizationContext: Parent Task {ParentTaskId}");
Debug.IndentLevel = 0;
SynchronizationHelper.ExecuteOnContext(ctxt, contextCallback, state);
}
else
{
Debug.WriteLine(string.Empty);
Debug.IndentLevel = 1;
Debug.WriteLine($"BrighterSynchronizationContext: Post Failed to queue {callback.Method.Name} on thread {Thread.CurrentThread.ManagedThreadId}");
Debug.WriteLine($"BrighterSynchronizationContext: Parent Task {ParentTaskId}");
Debug.IndentLevel = 0;
//just execute inline
SynchronizationHelper.ExecuteImmediately(contextCallback, state);
}

Debug.WriteLine(string.Empty);
Debug.IndentLevel = 1;
Debug.WriteLine($"BrighterSynchronizationContext: Post Failed to queue {callback.Method.Name} on thread {Thread.CurrentThread.ManagedThreadId}");
Debug.WriteLine($"BrighterSynchronizationContext: Parent Task {ParentTaskId}");
Debug.IndentLevel = 0;

//just execute inline
// current thread already owns the context, so just execute inline to prevent deadlocks
//if (BrighterSynchronizationHelper.Current == SynchronizationHelper)
//SynchronizationHelper.ExecuteImmediately(contextCallback, state);
//else
base.Post(callback, state);

}

Expand All @@ -186,8 +175,7 @@ public override void Send(SendOrPostCallback callback, object? state)
}
else
{
var ctxt = ExecutionContext.Capture();
var task = SynchronizationHelper.MakeTask(new ContextMessage(callback, state, ctxt));
var task = SynchronizationHelper.MakeTask(new ContextMessage(callback, state));
if (!task.Wait(Timeout)) // Timeout mechanism
throw new TimeoutException("BrighterSynchronizationContext: Send operation timed out.");
}
Expand Down
4 changes: 1 addition & 3 deletions src/Paramore.Brighter/Tasks/ContextMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ public struct ContextMessage
/// </summary>
/// <param name="callback">The callback to execute.</param>
/// <param name="state">The state to pass to the callback.</param>
/// <param name="ctxt">The execution context, mainly intended for debugging purposes</param>
public ContextMessage(SendOrPostCallback callback, object? state, ExecutionContext? ctxt)
public ContextMessage(SendOrPostCallback callback, object? state)
{
Callback = callback;
State = state;
Context = ctxt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -151,26 +151,26 @@ public void Current_WithoutAsyncContext_IsNull()
}

[Fact]
public void Current_FromAsyncContext_IsAsyncContext()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ Getting worse: Code Duplication
introduced similar code in: Current_FromBrighterSynchronizationHelper_IsBrighterSynchronizationHelper,SynchronizationContextCurrent_FromBrighterSynchronizationHelper_IsBrighterSynchronizationHelperSynchronizationContext

public void Current_FromBrighterSynchronizationHelper_IsBrighterSynchronizationHelper()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Getting better: Code Duplication
reduced similar code in: Current_FromAsyncContext_IsAsyncContext,SynchronizationContextCurrent_FromAsyncContext_IsAsyncContextSynchronizationContext,TaskSchedulerCurrent_FromAsyncContext_IsThreadPoolTaskScheduler

{
BrighterSynchronizationHelper observedContext = null;
var context = new BrighterSynchronizationHelper();
BrighterSynchronizationHelper observedHelper = null;
var helper = new BrighterSynchronizationHelper();

var task = context.Factory.StartNew(
() => { observedContext = BrighterSynchronizationHelper.Current; },
context.Factory.CancellationToken,
context.Factory.CreationOptions | TaskCreationOptions.DenyChildAttach,
context.TaskScheduler);
var task = helper.Factory.StartNew(
() => { observedHelper = BrighterSynchronizationHelper.Current; },
helper.Factory.CancellationToken,
helper.Factory.CreationOptions | TaskCreationOptions.DenyChildAttach,
helper.TaskScheduler);

context.Execute(task);
helper.Execute(task);

observedContext.Should().Be(context);
observedHelper.Should().Be(helper);
}

[Fact]
public void SynchronizationContextCurrent_FromAsyncContext_IsAsyncContextSynchronizationContext()
public void SynchronizationContextCurrent_FromBrighterSynchronizationHelper_IsBrighterSynchronizationHelperSynchronizationContext()
{
System.Threading.SynchronizationContext observedContext = null;
System.Threading.SynchronizationContext? observedContext = null;
var context = new BrighterSynchronizationHelper();

var task = context.Factory.StartNew(
Expand Down Expand Up @@ -360,6 +360,35 @@ public async Task Task_AfterExecute_Runs_On_ThreadPool()

threadPoolExceptionRan.Should().BeTrue();
}

[Fact]
public async Task SynchronizationContextCurrent_FromAsyncContext_PostFromAnotherThread()
{
System.Threading.SynchronizationContext? observedContext = null;
var helper = new BrighterSynchronizationHelper();

var task = helper.Factory.StartNew(
() => { observedContext =BrighterSynchronizationContext.Current; },
helper.Factory.CancellationToken,
helper.Factory.CreationOptions | TaskCreationOptions.DenyChildAttach,
helper.TaskScheduler);

//this should complete the task
helper.Execute(task);

//but this simulates us being disposed
observedContext.OperationCompleted();

//we may be called on a different thread
int value = 1;
await Task.Run(() =>
{
observedContext .Post(_ => value = 2, null);
});

value.Should().Be(2);

}

[Fact]
public void SynchronizationContext_IsEqualToCopyOfItself()
Expand Down