考虑使用异步等待处理输入和而你的UI线程执行其他任务更新的结果。
事件处理程序:
private async void OnButton1_clicked(object sender, ...)
{
var result = await ProcessInputAsync(...)
displayResult(result);
}
假设ProcessInputAsync是耗时的功能。 DisplayResult由UI线程调用,并且可以正常处理。
注意:所有异步函数都应该返回Task而不是void或任务<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元素尝试更新它。为此我们有调用模式:
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;
}
}
请显示真实代码而不是您在此处显示的伪代码。阅读http://tinyurl.com/so-hints –
我想我们需要看更多的代码才能诊断这个。 “线程的函数”实际上是如何写入的? –