我正在使用此解决方案: 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”正在下载文本之前打印,但需要一段时间(我认为它正在等待下载完全返回打印它。)我做错了什么?
答案 0 :(得分:0)
您的实施和期望是正确的。在调用实际的基础WebClient::DownloadStringTaskAsync
之前,WebRequest::BeginGetResponse
确实有一些同步操作,但很少。我看到的唯一一个可以解释代码发现/协商的代码。你是偶然的代理人吗?