繁体   English   中英

如何在 C# 中等待完成?

[英]How do I wait for something to finish in C#?

 private void Download_Click(object sender, EventArgs e)
        {
            label1.Text = "Downloading...";
            WebClient wc = new WebClient();
            string program = "Program";
            string link = "https://linkhere.com";
            string download = wc.DownloadString(link);
            string path = "Program\\" + program + ".zip";
            string patch = "Program";
            Directory.CreateDirectory(patch);
            wc.DownloadFile(download, path);
            label1.Text = "Downloaded!";
        }

我想让 label1.Text = "Downloaded;"。 下载程序后发生。

您需要使下载异步以防止死锁。

private async void Download_Click(object sender, EventArgs e)
{
    label1.Text = "Downloading...";
    WebClient wc = new WebClient();
    string program = "Program";
    string link = "https://linkhere.com";
    string download = wc.DownloadString(link);
    string path = "Program\\" + program + ".zip";
    string patch = "Program";
    Directory.CreateDirectory(patch);
    await wc.DownloadFileAsync(download, path);
    label1.Text = "Downloaded!";
}

DownloadFile 文档说“下载资源时此方法会阻塞”,所以我不确定您的情况可能有什么不同,或者是否存在问题。

我怀疑您永远不会看到"Downloading..." ,因为 UI 在两个label1.Text更新调用之间没有更新。 在第一次.Text更新后添加Application.DoEvents()可能会有所帮助。

请使用任务和事件来处理这种情况。

您可以将此作为参考修改您的下载。

    public static async Task Main()
    {
        Task task1 = new Task(() => ActionToWork1());
        Task task2 = new Task(() => ActionToWork2());
        
        task1.Start();
        task2.Start();
        await Task.WhenAll(task1, task2);
        Console.WriteLine("All task done.");    
    }
    
    private static void ActionToWork1(){
        Console.WriteLine("Working on Task 1"); 
    }
    
    private static void ActionToWork2(){
        Console.WriteLine("Working on Task 2"); 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM