我遇到线程问题,我想在收到短信时在txtoutput(文本框)上显示一个文字我已经完成了但是没有用。
private void Output(string text)
{
this.expander.IsExpanded = true; // Exception catched: The calling thread can not access this object because a different thread owns it.
if (txtOutput.Dispatcher.CheckAccess())
{
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
}
else
{
this.txtOutput.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
{
// txtOutput.AppendText += text Environment.NewLine;
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
});
}
}
答案 0 :(得分:2)
试试这个
private void Output(string text)
{
if (txtOutput.Dispatcher.CheckAccess())
{
this.expander.IsExpanded = true;
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
}
else
{
this.txtOutput.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
{
this.expander.IsExpanded = true;
// txtOutput.AppendText += text Environment.NewLine;
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
});
}
}
改进版本:
private void Output(string text)
{
if (!txtOutput.Dispatcher.CheckAccess())
{
this.txtOutput.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
{
Output(text); //Call this function again on the correct thread!
});
return;
}
this.expander.IsExpanded = true;
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
}
答案 1 :(得分:2)
您正在以正确的方式设置txtOutput
的文字(CheckAccess()
和BeginInvoke
)。对expander
执行相同的操作。