Async method not returning immediately [duplicate]

倖福魔咒の 提交于 2019-12-10 11:44:58

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!