Will Will - 1 year ago 102
C# Question

How do I ".Wait( )" on a ConfiguredTaskAwaitable?

Given the following extension to prevent

from blocking the UI Thread ( probably not the exact correct terminology but whatever ) :

public static ConfiguredTaskAwaitable DontBlock( this Task T ) {
return T.ConfigureAwait( false );

public static ConfiguredTaskAwaitable<T> DontBlock<T>( this Task<T> T2 ) {
return T2.ConfigureAwait( false );

In some cases ( such as if I need to call an awaitable within an object constructor, or if I need to call
.Wait( )
from a WinForms
Program.Main( )
method), I need to do the following :

public class Foo{
public Foo( ){
//I know full well that the result from DontBlock does not have a 'wait' method, so of course this will fail miserably.
AwaitableBar.DontBlock( ).Wait( );

How can I 'await' it outside an
function/method if I can't call
.Wait( )
on it? I see that it has a
.GetAwaiter( )
method which returns a
object, but I have no idea what to do with it, and Google has failed me again... Am I supposed to call
GetResult( )
on the returned object right away? Will doing that wait for everything to finish, or just skip right over it, or explode?

Answer Source

I agree with the @usr that returning a ConfiguredTaskAwaitable is not ideal. Generally, your asynchronous methods should return tasks. This is a matter of separation of concerns.

Once you have a ConfiguredTaskAwaitable, though, simply call awaitableObj.GetAwaiter().GetResult() (or the appropriate substitution). GetResult() will block.