gpt4 book ai didi

c# - 如何以异步方法向 UI 提供反馈?

转载 作者:太空狗 更新时间:2023-10-29 18:11:58 25 4
gpt4 key购买 nike

我一直在开发一个 Windows 窗体项目,我有 10 个任务要做,我想以 async 的方式来完成。当用户单击按钮时,这些任务将启动,我调用 async 方法来执行此操作。在我的代码中,我已经有了这些过程的参数列表。

我的问题是:

A) How transform my code to run all process in parallel? (I would like to implement async/await)

B) How to provide a feedback to my UI application?

下面的代码是我试过的:

我的按钮调用一个方法来启动进程

private void button1_Click(object sender, EventArgs e)
{
// almost 15 process
foreach (var process in Processes)
{
// call a async method to process
ProcessObject(process);
}
}

模拟我的进程获取参数的方法

private async void ProcessObject(ProcessViewModel process)
{
// this is my loop scope, which I need to run in parallel
{
// my code is here

// increment the progress of this process
process.Progress++;

// feedback to UI (accessing the UI controls)
UpdateRow(process);
}
}

我试过了,但我不确定这是否是更新我的 UI(网格)的正确方法。

private void UpdateRow(ProcessViewModel process)
{
dataGridView1.Rows[process.Index - 1].Cells[1].Value = process.Progress;
dataGridView1.Refresh();
}

最佳答案

Sriram 介绍了如何执行异步/等待 in his answer ,但是我想向您展示另一种方法,以他的回答为基础来更新 UI 线程上的进度。

.NET 4.5 添加了 IProgress<T> 接口(interface)和 Progress<T> 类(class)。内置的 Progress 类捕获同步上下文,就像 async/await 一样,然后当您报告进度时,它会使用该上下文进行回调(在您的例子中是 UI 线程)。

private async void button1_Click(object sender, EventArgs e)
{
var progress = new Progress<ProcessViewModel>(UpdateRow); //This makes a callback to UpdateRow when progress is reported.

var tasks = Processes.Select(process => ProcessObject(process, progress)).ToList();
await Task.WhenAll(tasks);
}

private async Task ProcessObject(ProcessViewModel process, IProgress<ProcessViewModel> progress)
{
// my code is here with some loops
await Task.Run(()=>
{
//Will be run in ThreadPool thread
//Do whatever cpu bound work here


//Still in the thread pool thread
process.Progress++;

// feedback to UI, calls UpdateRow on the UI thread.
progress.Report(process);
});
}

关于c# - 如何以异步方法向 UI 提供反馈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25745176/

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