2 回答
TA贡献1895条经验 获得超7个赞
试试这个:
1.添加以下使用: using System.ComponentModel;
2.声明后台工作者:
private readonly BackgroundWorker worker = new BackgroundWorker();
3.注册活动:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
4.实现两种方法:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
5.在需要时运行 worker async。
worker.RunWorkerAsync();
此外,如果您想报告流程进度,您应该订阅 ProgressChanged 事件并在 DoWork 方法中使用 ReportProgress(Int32) 来引发事件。还设置如下:worker.WorkerReportsProgress = true;
希望这有帮助。
TA贡献1820条经验 获得超2个赞
正确使用 async/await 模式,您根本不需要 Dispatcher:
private async void Button_Click(object sender, RoutedEventArgs e)
{
await Iterate_balance();
}
private async Task Iterate_balance()
{
button.Content = "Click to stop";
// some long async operation
await Task.Delay(TimeSpan.FromSeconds(4));
button.Content = "Click to run";
}
- 2 回答
- 0 关注
- 161 浏览
添加回答
举报