I am working from this solution: How to correctly write async method?
However, the async method does not seem to return immediately, rather it takes a while. Here is the
class Program
{
static void Main(string[] args)
{
Debug.WriteLine("Calling DoDownload");
var downloadTask = DoDownloadAsync();
Debug.WriteLine("DoDownload done");
downloadTask.Wait(); //Waits for the background task to complete before finishing.
}
private static async Task DoDownloadAsync()
{
WebClient w = new WebClient();
string txt = await w.DownloadStringTaskAsync("http://www.google.com/");
Debug.WriteLine(txt);
}
}
"DoDownload Done" is being printed before the download text, but it takes a while (I think it is waiting for the download to completely return to print it.) What am I doing wrong?
Your implementation and expectation is correct. WebClient::DownloadStringTaskAsync
does have some synchronous operations before the actual underlying WebRequest::BeginGetResponse
is called, but very few. The only one I see perusing through the code that might account for this proxy discovery/negotiation. Are you behind a proxy by chance?
来源:https://stackoverflow.com/questions/20888709/async-method-not-returning-immediately