gpt4 book ai didi

C# 等待异步操作完成

转载 作者:行者123 更新时间:2023-11-30 22:21:23 28 4
gpt4 key购买 nike

我想知道对于我正在尝试做的事情最好的方法是什么。我的应用程序有一个启动后台下载操作的按钮,然后根据下载的文件执行一些操作。

这就像“一旦下载必要的数据,游戏将很快开始”的情况,用户可能仍然使用主窗体。

private void btnStart_Click(object sender, EventArgs e)
{
//execute some code

Downloader.RunWorkerAsync(files); //this worker reports progress to the main form

while (Downloader.IsBusy)
Application.DoEvents();

//execute some more code
}

我知道这样做一点都不好。

我无法同步执行下载代码,因为主窗体需要在下载操作期间保持响应。我也无法将最终代码放入下载完成事件中,因为它被程序的许多其他区域使用并且必须保持“通用”下载系统。

那么,有没有办法做我想做的事?我对其他异步方法没有任何经验。

最佳答案

如果您使用 BackgrounWorker,您必须正确配置它。 BW 有 RunWorkerCompleted 事件,您必须订阅该事件才能处理异步工作的完成。

关于C# 等待异步操作完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14412048/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com