【问题标题】:How do I get my C# Async and Wait code to work?如何让我的 C# Async 和 Await 代码工作?
【发布时间】:2018-06-23 13:07:00
【问题描述】:

有人可以帮我解决这个问题吗 这是我的代码,我想让解压缩任务等待文件下载,但它不是一个,它不会让我等待一个空,我到处找,我想不通,所以有人可以把工作寄回给我代码感谢(请注意所有这些代码都有效,但不适用于异步):

        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileAsync(new Uri("https://webserver-test-1.000webhostapp.com/spacelightzipped.zip"), Environment.CurrentDirectory + "\\spacelightzipped.zip");

        String ZipPath = Environment.CurrentDirectory + "\\spacelightzipped.zip";
        String extractPath = Environment.CurrentDirectory;
        ZipFile.ExtractToDirectory(ZipPath, extractPath);

        System.Diagnostics.Process proc = new System.Diagnostics.Process
        {
            EnableRaisingEvents = false
        };
        proc.StartInfo.FileName = Environment.CurrentDirectory + "\\SpaceLightApp.exe";
        proc.Start();

【问题讨论】:

  • “它不允许我等待 void” 您可以只使用 Task 而不是 void,这样您就可以在调用它的地方等待。
  • @Thangadurai - 我认为 OP 指的是DownloadFileAsync
  • 如果您想查看我的所有代码,请输入here
  • 你不妨看看DownloadFileTaskAsync
  • @Damien_The_Unbeliever,啊..对不起,我错过了这一点。这个SO 帖子提供了一种解决方法。

标签: c# .net asynchronous async-await


【解决方案1】:

您必须使用事件WebClient.DownloadFileCompleted 事件,该事件将在文件完全下载时引发,然后在文件上执行您想要的任何代码。

所以你需要为你的 webClient 注册事件。 喜欢:

client.DownloadFileCompleted += wc_DownloadFileCompleted;

然后调用你的代码在DownloadFileCompleted事件中提取并执行。

private static void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            String ZipPath = Environment.CurrentDirectory + "\\spacelightzipped.zip";
            String extractPath = Environment.CurrentDirectory;
            ZipFile.ExtractToDirectory(ZipPath, extractPath);

            System.Diagnostics.Process proc = new System.Diagnostics.Process
              {
                 EnableRaisingEvents = false
              };
             proc.StartInfo.FileName = Environment.CurrentDirectory + "\\SpaceLightApp.exe";
             proc.Start();
        }

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2021-11-29
    • 2021-05-12
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2021-12-18
    相关资源
    最近更新 更多