Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await operator can only be used within an Async method [duplicate]

I'm trying to make a simple program to test the new .NET async functionality within Visual Studio 2012. I generally use BackgroundWorkers to run time-consuming code asynchronously, but sometimes it seems like a hassle for a relatively simple (but expensive) operation. The new async modifier looks like it would be great to use, but unfortunately I just can't seem to get a simple test going.

Here's my code, in a C# console application:

static void Main(string[] args) {     string MarsResponse = await QueryRover();     Console.WriteLine("Waiting for response from Mars...");     Console.WriteLine(MarsResponse);     Console.Read(); }  public static async Task<string> QueryRover() {     await Task.Delay(5000);     return "Doin' good!"; } 

I checked out some examples on MSDN and it looks to me like this code should be working, but instead I'm getting a build error on the line containing "await QueryRover();" Am I going crazy or is something fishy happening?

like image 588
William Thomas Avatar asked Aug 06 '12 21:08

William Thomas


People also ask

Why await can only be used in async function?

The "await is only valid in async functions" error occurs when the await keyword is used inside of a function that wasn't marked as async . To use the await keyword inside of a function, mark the directly enclosing function as async .

Can one async function have multiple awaits?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Can we await an async function?

If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back. If the promise rejects, the rejected value is thrown.

Can async be used without await?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.


1 Answers

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

like image 80
Stephen Cleary Avatar answered Sep 20 '22 21:09

Stephen Cleary