I’m making a web call using the async framework. I’m getting an Error noted in the code below
class Program
{
static void Main(string[] args)
{
TestAsync async = new TestAsync();
await async.Go();//Error: the await operator can only be used with an async method. Consider markign this method with the async modifier. Consider applying the await operator to the result of the call
}
}
class TestAsync
{
public async Task Go()
{
using (WebClient client = new WebClient())
{
var myString = await client.DownloadStringTaskAsync("http://msdn.microsoft.com");
Console.WriteLine(myString);
}
}
}
I’ve tried several variations of this code. It either fails at runtime or does not compile. In this case the method completes before my async call is allowed to fire. What am I doing wrong?
My goal is to execute a call to a web site using WebClient in an async fashion. I want to return the result as a string and print it out using Console.WriteLine. If you feel more comfortable starting with code that executes simply change
await async.Go(); to async.Go(); The code will run, but Console.WriteLine will not be hit.
The error message is correctly telling you that
awaitcan only be used inasyncmethods. But, you can’t makeMain()async, C# doesn’t support that.But
asyncmethods returnTasks, the sameTaskused in TPL since .Net 4.0. AndTasks do support synchronous waiting using theWait()method. So, you can write your code like this:Using
Wait()is the right solution here, but in other cases, mixing synchronous waiting usingWait()and asynchronous waiting usingawaitcan be dangerous and can lead to deadlocks (especially in GUI applications or in ASP.NET).