【问题标题】:error - the calling thread cannot access this object because a different thread owns it [duplicate]错误-调用线程无法访问此对象,因为不同的线程拥有它[重复]
【发布时间】:2013-08-27 09:36:09
【问题描述】:

我正在尝试从连接硬件的 PORT 获取值。我已成功从端口获取值,但是当我尝试填充此值时,它会出现以下错误

“调用线程无法访问此对象,因为不同的线程拥有它”

这是我的代码

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        string strAck = port.ReadExisting();

        if (!string.IsNullOrWhiteSpace(strAck))
        {
            txtvalue = strAck;            
        }
    }            
    catch(Exception ex)
    {    
    }
}

【问题讨论】:

  • 请参阅右侧的相关部分。这个问题之前回答过很多次了。
  • 还有一点谷歌可以走很长的路。通常,我会直接将异常文本复制到我的搜索引擎中,并且仅在我无法以这种方式解决问题时才提出问题。
  • 如果您使用的是 .NET 4.5,请尝试新的 await 和 async api,它使这个问题变得更容易。 msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

标签: wpf c#-4.0


【解决方案1】:

您确实应该在发布此问题之前搜索您的问题的答案,因为之前已在此处多次回答。简短的回答是您必须在 UI 线程上设置值。你可以这样做:

this.Dispatcher.Invoke((Action)(() =>
{
    string strAck = port.ReadExisting();
    if (!string.IsNullOrWhiteSpace(strAck))
    {
        txtvalue = strAck;            
    }
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多