We have a library that is being used by WPF and/or Winforms clients.
We've provided an asynchronous method similar to:
Task<int> GetIntAsync()
We've also (unfortunately) provided a synchronous wrapper method:
int GetInt();
which essentially just calls the asynchronous method and calls .Result
on its task.
We recently realized under certain circumstances some code in the GetIntAsync
needs to run on the main UI thread (it needs to use a legacy COM component that is marked as "Single" Threading model (i.e. the component must run in the main STA thread not just any STA thread)
So the problem is that when GetInt()
is called on the main thread, it will deadlock since
.Result
blocks the main thread, GetIntAsync()
uses Dispatcher.Invoke
to attempt to run on the main thread.The synchronous method is already being consumed so it would be a breaking change to remove it. So instead, we've opted for using the WaitWithPumping in our synchronous GetInt()
method to allow the invoking to the main thread to work.
This works fine except for clients that use GetInt()
from their UI code. Previously, they expected that using GetInt()
would leave their UI unresponsive--that is, if they called GetInt()
from within a button's click event handler, they would expect that no windows messages were processed until the handler returned. Now that messages are pumped, their UI is responsive and that same button can be clicked again (and they probably didn't code their handler to be re-entrant).
If there is a reasonable solution, we'd like to not have our clients need to code against the UI being responsive during a call to GetInt
Question:
WaitWithPumping
that will pump "Invoke to main" messages, but not pump other UI related messages?Rather than utilizing the existing message pump you can create your own message pump within the context of GetInt
. Here is a blog entry discussing how to write one. This is the full solution the blog creates.
Using that you can write it as:
public int GetInt()
{
return AsyncPump.Run(() => GetIntAsync());
}
That will result in completely blocking the UI thread as expected, while still ensuring that all continuations called from GetIntAsync
don't deadlock as they'll be marshaled to a different SynchronizationContext
. Also note that this message pump is still running on the main STA/UI thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With