本文介绍了异步方法不是立即返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这个解决方案的工作:

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完成下载文本之前,但它需要一段时间(我认为这是等待下载,完全恢复到打印出来。)我在做什么错了?

"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?

推荐答案

您的实现和期望是正确的。 的WebClient :: DownloadStringTaskAsync 确实有实际的基础的WebRequest :: BeginGetResponse 之前的一些同步操作被称为,但很少。唯一一个我看透code可能解释这种代理发现/谈判细读。你身后是偶然的代理?

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?

这篇关于异步方法不是立即返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:00