异步方法不立即返回

时间:2014-01-02 17:50:11

标签: c# async-await c#-5.0

我正在使用此解决方案: How to correctly write async method?

但是,异步方法似乎不会立即返回,而是需要一段时间。这是

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”正在下载文本之前打印,但需要一段时间(我认为它正在等待下载完全返回打印它。)我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的实施和期望是正确的。在调用实际的基础WebClient::DownloadStringTaskAsync之前,WebRequest::BeginGetResponse确实有一些同步操作,但很少。我看到的唯一一个可以解释代码发现/协商的代码。你是偶然的代理人吗?