Mar*_*knk 5 c# asynchronous winforms async-await
我有一个包含Button和RichTextBox控件的WinForms应用程序.用户单击Button后,将执行IO要求操作.为了防止阻塞UI线程,我实现了async/await模式.我还想将此操作的进度报告给RichTextBox.这就是简化逻辑的样子:
private async void LoadData_Click(Object sender, EventArgs e)
{
this.LoadDataBtn.Enabled = false;
IProgress<String> progressHandler = new Progress<String>(p => this.Log(p));
this.Log("Initiating work...");
List<Int32> result = await this.HeavyIO(new List<Int32> { 1, 2, 3 }, progressHandler);
this.Log("Done!");
this.LoadDataBtn.Enabled = true;
}
private async Task<List<Int32>> HeavyIO(List<Int32> ids, IProgress<String> progress)
{
List<Int32> result = new List<Int32>();
foreach (Int32 id in ids)
{
progress?.Report("Downloading data for " + id);
await Task.Delay(500); // Assume that data is downloaded from the web here.
progress?.Report("Data loaded successfully for " + id);
Int32 x = id + 1; // Assume some lightweight processing based on downloaded data.
progress?.Report("Processing succeeded for " + id);
result.Add(x);
}
return result;
}
private void Log(String message)
{
message += Environment.NewLine;
this.RichTextBox.AppendText(message);
Console.Write(message);
}
Run Code Online (Sandbox Code Playgroud)
操作成功完成后,RichTextBox包含以下文本:
Initiating work...
Downloading data for 1
Data loaded successfully for 1
Processing succeeded for 1
Downloading data for 2
Data loaded successfully for 2
Processing succeeded for 2
Downloading data for 3
Done!
Data loaded successfully for 3
Processing succeeded for 3
Run Code Online (Sandbox Code Playgroud)
如您所见,之后报告了第3个工作项的进度Done!.
我的问题是,导致延迟进度报告的原因是什么LoadData_Click?只有在报告了所有进展后,我才能实现这种意愿流程?
Progressclass将在创建时捕获当前同步上下文,然后将回调发布到该上下文(这在该类的文档中说明,或者您可以查看源代码).在你的情况下,这意味着WindowsFormsSynhronizationContext被捕获,并且发布到它就像做事一样粗鲁Control.BeginInvoke().
await还捕获当前上下文(除非您使用ConfigureAwait(false))并将向其发布方法的延续.对于除了last之外的迭代,UI线程被释放await Task.Delay(500);,因此可以处理您的报告回调.但是在foreach循环的最后一次迭代中会发生以下情况:
// context is captured
await Task.Delay(500); // Assume that data is downloaded from the web here.
// we are now back on UI thread
progress?.Report("Data loaded successfully for " + id);
// this is the same as BeginInvoke - this puts your callback in UI thread
// message queue
Int32 x = id + 1; // Assume some lightweight processing based on downloaded data.
// this also puts callback in UI thread queue and returns
progress?.Report("Processing succeeded for " + id);
result.Add(x);
Run Code Online (Sandbox Code Playgroud)
因此,在上一次迭代中,您的回调被放入UI线程消息队列,但它们现在无法执行,因为您在此同时在UI线程中执行代码.当代码到达时this.Log("done")- 它被写入您的日志控件(BeginInvoke此处不使用).然后在你的LoadData_Click方法结束之后 - 只有在此时才释放UI线程执行你的代码并且可以处理消息队列,所以你的2个回调在那里等待解决.
鉴于所有这些信息 - 就像LogEnigmativity在评论中所说的那样 - 没有必要在Progress这里使用课程.