Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

Commit

Permalink
Avoid unnecessarily propagating ExecutionContext in SocketAsyncEngine (
Browse files Browse the repository at this point in the history
…#28676)

SocketAsyncEngines are created lazily on-demand.  If we happen to create one at a point where there's a non-default ExecutionContext, we end up capturing that context onto the event loop thread, such that all subsequent dispatches capture and restore that ExecutionContext.
  • Loading branch information
stephentoub authored Mar 31, 2018
1 parent fe0edc4 commit ec5fb41
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public bool TryCancel()
// we can't pool the object, as ProcessQueue may still have a reference to it, due to
// using a pattern whereby it takes the lock to grab an item, but then releases the lock
// to do further processing on the item that's still in the list.
ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(allowPooling: false), this);
ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(allowPooling: false), this);
}

Trace("Exit");
Expand Down Expand Up @@ -837,7 +837,7 @@ public void HandleEvent(SocketAsyncContext context)

// We just transitioned from Waiting to Processing.
// Spawn a work item to do the actual processing.
ThreadPool.QueueUserWorkItem(s_processingCallback, context);
ThreadPool.UnsafeQueueUserWorkItem(s_processingCallback, context);
}

// Called on the threadpool when data may be available.
Expand Down Expand Up @@ -968,7 +968,7 @@ public void ProcessQueue(SocketAsyncContext context)
Debug.Assert(_state == QueueState.Processing);

// Spawn a new work item to continue processing the queue.
ThreadPool.QueueUserWorkItem(s_processingCallback, context);
ThreadPool.UnsafeQueueUserWorkItem(s_processingCallback, context);
}

// At this point, the operation has completed and it's no longer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,11 +286,21 @@ private SocketAsyncEngine()
//
// Start the event loop on its own thread.
//
Task.Factory.StartNew(
EventLoop,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
bool suppressFlow = !ExecutionContext.IsFlowSuppressed();
try
{
if (suppressFlow) ExecutionContext.SuppressFlow();
Task.Factory.StartNew(
s => ((SocketAsyncEngine)s).EventLoop(),
this,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
finally
{
if (suppressFlow) ExecutionContext.RestoreFlow();
}
}
catch
{
Expand Down

0 comments on commit ec5fb41

Please sign in to comment.