Await operator can only be used within an Async method

C#.NetBuild.Net 4.5Async Await

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliam ThomasView Question on Stackoverflow
Solution 1 - C#Stephen ClearyView Answer on Stackoverflow