考虑在 UI 线程执行其他操作时使用 async-await 处理输入并更新结果。
事件处理程序:
private async void OnButton1_clicked(object sender, ...)
{
var result = await ProcessInputAsync(...)
displayResult(result);
}
假设 ProcessInputAsync 是耗时的函数。DisplayResult由UI线程调用,可以正常处理。
注意:所有异步函数都应该返回 Task 而不是 void 或 Task <Tresult
> 而不是 TResult。有一个例外:异步事件处理程序应该返回 void 而不是 Task。
private async Task<TResult> ProcessInputAsync(...)
{
return await Task.Run( () => LengthyProcess(...)
}
private TResult LengthyProcess(...)
{
// this is the time consuming process.
// it is called by a non-ui thread
// the ui keeps responsive
TResult x = ...
return x;
}
如果您真的不想等待冗长的过程完成,但您希望另一个线程更新 UI,您会收到一个运行时错误,即未创建 UI 元素的线程尝试更新它。为此,我们有调用模式:
private void UpdateMyTextBox(string myTxt)
{
if (this.InvokeRequired)
{ // any other thread than the UI thread calls this function
// invoke the UI thread to update my text box
this.Invoke(new MethodInvoker(() => this.UpdateMyTextBox(myTxt));
}
else
{
// if here: this is the UI thread, we can access the my text box
this.TextBox1.Text = myTxt;
}
}