【发布时间】:2014-01-07 01:44:34
【问题描述】:
所以我正在尝试学习在 C# 中使用“异步”和“等待”的基础知识,但我不确定我在这里做错了什么。我期待以下输出:
Calling DoDownload
DoDownload done
[...output here...]
但我没有得到下载的输出,我也期待“完成”,但这需要一段时间。不应该立即输出吗?另外,我似乎也无法得到字符串结果。这是我的代码:
namespace AsyncTest
{
class Program
{
static void Main(string[] args)
{
Debug.WriteLine("Calling DoDownload");
DoDownloadAsync();
Debug.WriteLine("DoDownload done");
}
private static async void DoDownloadAsync()
{
WebClient w = new WebClient();
string txt = await w.DownloadStringTaskAsync("http://www.google.com/");
Debug.WriteLine(txt);
}
}
}
【问题讨论】:
-
永远不要写异步 void。您的进程在完成之前退出。您不能在控制台应用程序中执行这样的异步操作。
-
@SLaks,
async void在这种特殊情况下是不合适的(事实上,在大多数情况下)。但是,我仍然反对使用never这个词。在适当的情况下,它是一种有效的工具。
标签: c# async-await c#-5.0