Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't await awaitable?

Tags:

c#

async-await

Visual Studio complains on the following:

public RelayCommand SendRegistrationCommand { get; private set; }
public async void SendRegistration()
{
    HttpClient client = new HttpClient();
    var response = await client.GetStringAsync("url");

    // ... todo
}

Cannot await 'System.Threading.Tasks.Task<string>'

I thought I've done this before, GetStringAsync is not awaitable?

like image 729
Jason94 Avatar asked Nov 21 '13 12:11

Jason94


People also ask

What happens if you don't await?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call.

How do you use await properly?

async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What does await () do in Java?

The await() method of the Java CyclicBarrier class is used to make the current thread waiting until all the parties have invoked await() method on this barrier or the specified waiting time elapses.

Can you await a void method?

For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited. Any caller of such a method must continue to completion without waiting for the called async method to finish.


1 Answers

You're probably targeting .NET 4.0.

If you can, switch to .NET 4.5 which supports async/await semantics.

If you can't, consider using the Async Targeting Pack: https://www.nuget.org/packages/Microsoft.CompilerServices.AsyncTargetingPack

Edit

As per the comments, Microsoft.Bcl.Async should be used instead: https://www.nuget.org/packages/Microsoft.Bcl.Async

like image 159
dcastro Avatar answered Oct 15 '22 10:10

dcastro