Task.wait 没有像我想象的那样工作 [英] Task.wait not working as I imagined

查看:28
本文介绍了Task.wait 没有像我想象的那样工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试下载文件,等待文件下载完成,然后再读取文件.我有以下方法来做到这一点:

I am trying to download a file, wait for the file to finish downloading, and then read the file afterwards. I have the following methods to do this:

private async Task startDownload(string link, string savePath)
{      
        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
        await client.DownloadFileTaskAsync(new Uri(link), savePath);              
}

private void checkUpdateButton_Click(object sender, EventArgs e)
{           
    Task task = Task.Factory.StartNew(() => startDownload(versionLink, versionSaveTo));
    task.Wait();

    if (task.IsCompleted)
    {
        checkVersion();
    }
}

checkVersion() 方法读取下载的文件.这是抛出一个 IOException 表示该文件正在被其他东西使用并且无法读取.我认为使用 task.Wait 会阻止方法的其余部分执行,直到任务完成?

The checkVersion() method reads the file that was downloaded. This is throwing an IOException saying that the file is in use by something else and cannot be read. I thought that having task.Wait would prevent the rest of the method from executing until the task was finished?

推荐答案

Task.Wait 将阻塞当前线程(在本例中为 UI 线程)并等待任务完成.在这种情况下,任务正在完成并出现错误,因此 Task.Wait 将抛出包含在 AggregateException 中的错误.

Task.Wait will block the current thread (in this case, the UI thread) and wait until the task is completed. In this case, the task is completing with an error, so Task.Wait will throw that error wrapped in an AggregateException.

正如其他人所指出的,您应该使用 await 而不是 Wait.此外, DownloadFileCompleted 没有意义,因为您使用的是 DownloadFileTaskAsync(而不是 DownloadFileAsync);并且 StartNew 是不必要的,因为下载是异步的.

As others noted, you should be using await instead of Wait. Also, DownloadFileCompleted doesn't make sense since you're using DownloadFileTaskAsync (and not DownloadFileAsync); and StartNew is unnecessary since the download is asynchronous.

哦,让我们处理 WebClient 并确保我们的命名约定遵循 基于任务的异步模式.

Oh, and let's dispose the WebClient and ensure our naming convention follows the Task-based Asynchronous Pattern.

private async Task startDownloadAsync(string link, string savePath)
{      
  using (var client = new WebClient())
  {
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
    await client.DownloadFileTaskAsync(new Uri(link), savePath);              
  }
}

private async void checkUpdateButton_Click(object sender, EventArgs e)
{           
  await startDownloadAsync(versionLink, versionSaveTo);
  checkVersion();
}

这篇关于Task.wait 没有像我想象的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆