Skip to content

Conversation

@11v1
Copy link

@11v1 11v1 commented Jan 29, 2026

Apparently, the existing implementation does not account for applications with a synchronization context. Most methods lack ConfigureAwait calls, which causes continuations to capture the current synchronization context and resume execution on a context-specific thread.

This behavior is important for UI applications, where continuations may resume on the UI thread and, in certain scenarios (especially sync-over-async), can lead to deadlocks. For general-purpose library code, it is recommended to use ConfigureAwait(false) to avoid context capture and remain environment-agnostic.

This PR changes:

  • ConfigureAwait(false) was added to all awaited asynchronous method calls, except in test projects.
  • The solution was configured to treat missing ConfigureAwait usage as an error to prevent future omissions. This rule is enabled for all projects except tests.

@dotnet-policy-service
Copy link

@11v1 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the .NET Foundation ( “.NET Foundation” ) for Your contributions to
.NET Foundation open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to .NET Foundation under this Agreement.

“Project” means any of the projects owned or managed by .NET Foundation and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant .NET Foundation, and those who receive the Submission directly
or indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant .NET Foundation, and those who receive the Submission directly or
indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to .NET Foundation. You agree to notify .NET Foundation in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by .NET Foundation.

.NET Foundation dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

@11v1 11v1 force-pushed the Context-agnostic-async-methods-continuation branch from cf0833a to 6a72225 Compare January 29, 2026 16:40
@mconnew
Copy link
Member

mconnew commented Jan 29, 2026

Using ConfigureAwait(false) is the typical recommendation for async code. At the time WCF was being ported to .NET [Core], there weren't all the code analyzers available now to catch when you missed a ConfigureAwait call. In addition to that, if you have an async method with for example 5 calls to async methods that need to be awaited, the ConfigureAwait call is only needed the first time one of the async method calls doesn't complete synchronously. You need to "fix up" the continuation for the first time it goes async, but subsequent await's don't need the fixup. Overall this results in a lot of extra time being spent checking the result of the async call, seeing it completed synchronously, and ending up being a no-op, or seeing it's an asynchronous completion, but you're on the worker thread pool anyway so it being a no-op.
It's a LOT of additional work which is only needed to be done if you are using a non-default synchronization context, AND it's the first async call to be awaited that actually completed asynchronously.

Instead of the (at the time) risk of missing adding ConfigureAwait which could result in a regression breaking someone, WCF Client went a different path. WCF will always go async for any channel proxy call. Even if the outgoing request is able to be sent synchronously (e.g. the OS buffers the outgoing payload on the socket), we are going to be asynchronously waiting for the reply anyway. There's no point in trying to avoid an unnecessary thread hop as we're going to have that happen anyway at some point. What we do instead is at the earliest opportunity, we forcibly jump threads to a worked thread on the threadpool. We drop the execution context so we don't flow the SynchronizationContext. This means we don't need to ever call ConfigureAwait once we're past this point as it will always be a no-op due to already being on the default worker threadpool.
We have tests to explicitly check that this happens. We use a single threaded SynchronizationContext that we execute some tests inside and make sure the call completes without blocking. The risk of not calling ConfigureAwait is that the continuation will be scheduled to the SynchronizationContext, and if it's single threaded, calling Wait() on the returned Task will cause a deadlock as you are holding the thread with the Wait() call, and the continuations can't progress. By forcing continuations to the worker threadpool before any actual async operations are possible, we guarantee we aren't going to deadlock on a single threaded SynchronizationContext. This means we never need to call ConfigureAwait. We avoid all the overhead of that call that's only needed in a very small percentage of the times it would get called, and don't have to worry about having missed calling it when code is changed.

If you are having a problem which you think is caused by WCF not using ConfigureAwait, it's almost certainly not caused by that. If your problem goes away after applying these changes, it's more likely there's a race condition in your code that the extra overhead is changing the timing of and you are now avoiding. We have pretty robust tests around this. The only way you could have a problem is if you are using the WCF channel stack without a channel proxy (raw Message calls using a channel created from a raw ChannelFactory created directly from Binding.CreateChannelFactory). If this is your scenario, let me know and I can help.

Basically, this isn't a problem, can you describe what symptoms you are seeing that you are trying to fix?

@11v1
Copy link
Author

11v1 commented Jan 30, 2026

@mconnew, thank you for the detailed answer. Your assumption about our usage of WCF without a channel proxy is correct - we create the channel directly via ChannelFactory.
The problem this change addresses is a System.TimeoutException that we encounter when using NetNamedPipe. After several successful sends, we start seeing:
System.TimeoutException: Sending to via * timed out after 00:01:00. The time allotted to this operation may have been a portion of a longer timeout.

Our investigation showed that System.ServiceModel.Channels.TransportDuplexSessionChannel.OnSend fails to acquire its semaphore. The semaphore is already held by another task, with the following stack trace:

>	[Async] System.ServiceModel.NetNamedPipe.dll!System.ServiceModel.Channels.PipeConnection.WriteAsync(System.ReadOnlyMemory<byte> buffer, bool immediate, System.TimeSpan timeout) Line 174	C#
 	[Async] System.ServiceModel.NetFramingBase.dll!System.ServiceModel.Channels.BufferedConnection.WriteNowAsync(System.ReadOnlyMemory<byte> buffer, System.TimeSpan timeout) Line 153	C#
 	[Async] System.Net.Security.dll!System.Net.Security.NegotiateStream.WriteAsync<System.Net.Security.AsyncReadWriteAdapter>(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken)	Unknown
 	[Async] System.ServiceModel.NetFramingBase.dll!System.ServiceModel.Channels.StreamConnection.WriteAsync(System.ReadOnlyMemory<byte> buffer, bool immediate, System.TimeSpan timeout) Line 311	C#
 	[Async] System.ServiceModel.NetFramingBase.dll!System.ServiceModel.Channels.TransportDuplexSessionChannel.OnSendAsync(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) Line 436	C#
 	[Async] System.ServiceModel.Primitives.dll!System.Runtime.TaskHelpers.ToApm.AnonymousMethod__2_1(System.Threading.Tasks.Task antecedent, object obj) Line 113	C#

Adding ConfigureAwait(false) to the async methods along this path resolves the issue entirely - we no longer observe deadlocks. Based on our analysis, this does not appear to be a thread race condition. It’s also worth noting that switching the transport to NetTcp eliminates the problem without any code changes.

The reason I opted to add ConfigureAwait(false) broadly is that it’s a safe and defensive approach. It avoids the need to reason about whether a method is a public API / WCF entry point, or an internal method that is only ever called after the execution context has already been dropped. That distinction requires fairly deep knowledge of the WCF execution model, and it’s easy for a specific call path to be overlooked - which may be what happened here.

You may be right that our usage is incorrect; however, a few observations still stand:

  • The current WCF client implementation can resume execution on the UI thread, whereas the same code used in any other application with no synchronization context continues on a thread pool thread.
  • The identical code path works without deadlocks on .NET Framework 4.8.

@11v1
Copy link
Author

11v1 commented Jan 30, 2026

StackTrace is before the previous one:

>	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.OutputChannel.BeginSend(System.ServiceModel.Channels.Message message, System.TimeSpan timeout, System.AsyncCallback callback, object state) Line 27	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Dispatcher.DuplexChannelBinder.BeginRequest(System.ServiceModel.Channels.Message message, System.TimeSpan timeout, System.AsyncCallback callback, object state) Line 370	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.StartSend(bool completedSynchronously) Line 1849	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.Begin() Line 1714	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannel.BeginCall(string action, bool oneway, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, System.TimeSpan timeout, System.AsyncCallback callback, object asyncState) Line 709	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannel.BeginCall(System.ServiceModel.Channels.ServiceChannel channel, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, System.AsyncCallback callback, object asyncState) Line 670	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.CreateGenericTask(System.ServiceModel.Channels.ServiceChannel channel, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] inputParameters) Line 197	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.CreateTask(System.ServiceModel.Channels.ServiceChannel channel, System.ServiceModel.Channels.MethodCall methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation) Line 169	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannelProxy.InvokeTaskService(System.ServiceModel.Channels.MethodCall methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation) Line 329	C#
 	System.ServiceModel.Primitives.dll!System.ServiceModel.Channels.ServiceChannelProxy.Invoke(System.Reflection.MethodInfo targetMethod, object[] args) Line 150	C#

If ServiceChannelProxy.Invoke is called from the UI thread, we get a deadlock. The reason why we don't deadlock on NetTcp is because System.Net.Sockets.Socket.SendAsync in System.ServiceModel.Channels.SocketAwaitableEventArgs.SendAsync always finishes synchronously (in my environment), while System.IO.Pipes.PipeStream.WriteAsync in System.ServiceModel.Channels.PipeConnection.WriteAsync finishes asynchronously.

Possibly, this particular execution path is missing a switch to the worker thread.

@mconnew
Copy link
Member

mconnew commented Jan 30, 2026

The call stack is going to help, I should be and to work out a fix.

@mconnew
Copy link
Member

mconnew commented Jan 30, 2026

I think the issue is I only implemented this for request/reply channel shapes, and it didn't get added to the IOutputChannel shaped channels, which we got away with due to SocketAwaitableEventArgs.SendAsync completing synchronously. Can you try adding await TaskHelpers.EnsureDefaultTaskScheduler(); to TransportDuplexSessionChannel.OnSendAsync before the call to await SendLock.WaitAsync. This won't be sufficient to fix everything as this would still result in a deadlock on the sync code path, but as you're calling a Task based async method, it should fix it for your call path.

@mconnew
Copy link
Member

mconnew commented Jan 30, 2026

By the way, as a temporary workaround, you can do this:

var result = await Task.Run(() => channel.DoSomethingAsync());

This would effectively do the same thing we're doing deeper into our code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants