如何使C#异步和等待代码正常工作?

时间:2018-06-23 13:07:00

标签: c# .net asynchronous async-await

有人可以帮我吗 这是我的代码,我想让解压缩任务等待文件下载,但不是,并且它不会让我等待空白,我到处都看了看,我无法弄清楚,所以有人可以将我寄回给我代码谢谢(请注意,所有这些代码都可以使用,但不能与异步代码一起使用):

        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();

1 个答案:

答案 0 :(得分:0)

您必须使用事件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();
        }