我在这里有以下代码:
public class ProcessTaskAsyncExProgress
{
public int ProgressPercentage { get; set; }
public string Text { get; set; }
}
public static class ProcessTask
{
public static async Task<string> Start(IProgress<ProcessTaskAsyncExProgress> progress)
{
const int total = 10;
for (var i = 0; i <= total; i++)
{
Thread.Sleep(300);
if (progress != null)
{
var args = new ProcessTaskAsyncExProgress
{
ProgressPercentage = (int)(i / (double)total * 100.0),
Text = "processing " + i
};
progress.Report(args);
}
}
return "Done";
}
}
在 Form1.cs 中
private async void button1_Click(object sender, EventArgs e)
{
var result = await StartTask();
}
private async Task<string> StartTask()
{
var progress = new Progress<ProcessTaskAsyncExProgress>();
progress.ProgressChanged += (s, e) =>
{
progressBar1.Value = e.ProgressPercentage;
listBox1.Items.Add(e.Text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
};
return await ProcessTask.Start(progress);
}
我遇到的问题是进度条和列表框在循环运行时没有填充。UI 仅在整个循环完成后更新,显示的是列表视图中的 10 个项目和一个 100% 的进度条。
我的代码应该如何使 UI 线程不挂起?