vic*_*jia 3 c# async-await c#-5.0
所以我想学习在C#中使用'async'和'await'的基础知识,但我不确定我在这里做错了什么.我期待以下输出:
Calling DoDownload
DoDownload done
[...output here...]
Run Code Online (Sandbox Code Playgroud)
但我没有得到下载的输出,我也期望"完成",但这需要一段时间.不应该立即输出吗?另外,我似乎也无法获得字符串结果.这是我的代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要获得所需的行为,您需要在退出之前等待该过程完成Main().为了能够告诉您的进程何时完成,您需要从函数返回a Task而不是a void,除非您正在处理事件,否则不应该void从async函数返回.
正确运行的程序的重写版本将是
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);
}
}
Run Code Online (Sandbox Code Playgroud)
因为你不能await在Main()我不得不做这个Wait()功能.如果这是一个具有SynchronizationContext的应用程序,我会await downloadTask;改为执行此函数async.