为什么在使用 webclient 下载文件时,它不会在一毫秒后下载并到达已完成的事件?

Why when using webclient to download a file it's not downloading and getting to the completed event after a millisecond?

首先我都试过了:

DownloadProgressChangedEventHandler 和 AsyncCompletedEventHandler 有点不起作用。 然后我都试了:

client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;

这次它立即进入完成的事件,它没有下载也没有更新 progressBar1。

private void Download()
        {
            WebClient client = new WebClient();
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += Client_DownloadProgressChanged;
            client.DownloadFileCompleted += Client_DownloadFileCompleted;
            client.DownloadFileAsync(new Uri("https://speed.hetzner.de/10GB.bin"), desktop);
        }

        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            label1.Text = "Download Completed";
        }

        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Maximum = (int)e.TotalBytesToReceive / 100;
            progressBar1.Value = (int)e.BytesReceived / 100;
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Maximum = (int)e.TotalBytesToReceive / 100;
            progressBar1.Value = (int)e.BytesReceived / 100;
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Download();
        }

声明button1_ClickDownload方法是async并在client.DownloadFileAsync之前添加await

或者你可以使用同步版本client.DownloadFile