Reputation: 44295
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.
Upvotes: 1
Views: 181
Reputation: 245028
The error message is correctly telling you that await
can only be used in async
methods. But, you can't make Main()
async
, C# doesn't support that.
But async
methods return Task
s, the same Task
used in TPL since .Net 4.0. And Task
s do support synchronous waiting using the Wait()
method. So, you can write your code like this:
class Program
{
static void Main(string[] args)
{
TestAsync async = new TestAsync();
async.Go().Wait();
}
}
Using Wait()
is the right solution here, but in other cases, mixing synchronous waiting using Wait()
and asynchronous waiting using await
can be dangerous and can lead to deadlocks (especially in GUI applications or in ASP.NET).
Upvotes: 2
Reputation: 5439
The program is ending before the web request can complete. This is because the Main will not wait for the async operation to complete since it has nothing left to do.
I bet if you make the Main last longer, then Console.WriteLine
will get called.
I'd try adding a sleep after the call to the async method - Thread.Sleep(500)
- anything long enough to permit the web request to complete should work.
Upvotes: -1