0

我的线程有问题,当我收到一条短信时,我想在我的 txtoutput(textbox) 上显示一个文本,但我已经这样做了,但不起作用。

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");
         }); 
    }
}
4

2 回答 2

2

您正在txtOutput以正确的方式(CheckAccess()BeginInvoke)设置文本。对 .做同样的事情expander

于 2013-06-24T09:21:55.883 回答
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");
}
于 2013-06-24T09:21:29.033 回答