C# 等待后的代码不';行不通
我有下一个代码:C# 等待后的代码不';行不通,c#,asynchronous,async-await,C#,Asynchronous,Async Await,我有下一个代码: static void Main() { Program.DownloadFile(); Console.ReadKey(); } static async Task DownloadFile() { using(WebClient wc = new WebClient()) { string address = "http://www.phantast
static void Main()
{
Program.DownloadFile();
Console.ReadKey();
}
static async Task DownloadFile()
{
using(WebClient wc = new WebClient())
{
string address = "http://www.phantastike.com/link/astrology/predictive_astrology_a.zip";
await wc.DownloadFileTaskAsync(address, "f.zip");
// Here method returns
}
Console.WriteLine("This line not reached");
}
当我启动它时,程序从未到达Console.WriteLine方法。等待之后它又回来了。
但在下一段代码中,它运行良好:
static void Main(string[] args)
{
Program.DownloadFile();
Console.ReadKey();
}
static async Task DownloadFile()
{
await Task.Factory.StartNew(() => Task.Delay(2000));
Console.WriteLine("Now you can see this message on console");
}
谁能解释呢?感谢您并为我的英语感到抱歉这里的
wait
用法没有问题。您应该监视正在下载的文件的下载进度。添加DownloadProgressChanged
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
string address = "http://www.ayobamiadewole.com/Blog/Files/AOP.zip";
await wc.DownloadFileTaskAsync(address, "f.zip");
}
static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("\r{0} % Completed.", e.ProgressPercentage);
}
这就是可能发生的情况:您不必等待
DownloadFile
完成,控件返回到Main
,您到达控制台。ReadKey
,您按下一个键,程序在有机会完成下载之前结束
当您使用wait Task.Factory.StartNew(()=>Task.Delay(2000))时
相反,您并没有真正等待整整2秒钟,因为Task.Factory.StartNew
返回一个Task
所以控制台。WriteLine
会立即到达。您需要使用任务。请改为运行
问题是,您没有等待操作完成。通常,您可以使用Wait执行此操作,但不能在Main
中使用,因此在本例中,只需使用任务。Wait
:
static void Main()
{
DownloadFile().Wait();
}
你确定它没有下载吗?无法重现您的问题。你知道它实际保存zip文件的位置吗?试着在try catch中覆盖它。在那里你可以看到文件是否被下载,而不是Task.Delay(),抛出一个异常来重新处理你的问题。您不必等待异步方法完成,就不会看到它失败。