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.
Main()doesn't make any sense. What do you expect it to do?usingis not necessary withWebClient. Most of the time, you should make sure that youDispose()anything that implementsIDisposable, butWebClienthas it only because its base (Component) does.