After spending far too much time trying to sort out async/await hell we're trying to get a standard for when we have to call an async method on a library we don't control and where there is no non-async method provided and get async out of our code all together.
I don't want a discussion of the merits of this I'm sure that for some people async/await works, just a foolproof way of calling any async method and not getting deadlocks etc.
Does
public someObject SomeFunction(string parameter)
{
return Task.Run(() => 3rdPartyLib.SomeFunctionAsync(parameter)).Result;
}
and
public void SomeMethod()
{
return Task.Run(() => 3rdPartyLib.SomeMethodAsync()).Wait;
}
Do the job? Do I need to configureAwait(false)? Will exceptions work normally?
Well, writing synchronous wrappers for asynchronous methods is an antipattern , too.
That said, there are a variety of hacks covered in my Brownfield Async article . The one you propose - the "thread pool hack" - will work unless the third party library requires use of the current context. Eg, if it is a method that expects to run in a scenario where it has access to UI controls, or if it expects to have HttpContext.Current
. Most libraries do not require this, so this hack would work for them.
There is no hack that works everywhere, in all scenarios.
You do not need ConfigureAwait(false)
. There is no await
to configure.
For exceptions, you should use GetAwaiter().GetResult()
instead of Result
and Wait()
. That prevents exceptions from being wrapped in AggregateException
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.