C#:调用线程无法访问此对象,因为另一个线程拥有它

C#: The calling thread cannot access this object because a different thread owns it

我知道这个问题已经回答了 before。但我在我的项目中尝试过,它抛出异常。我是 C# 的新手,我想知道哪里做错了。提前致谢。

问题: 我正在尝试更新对话框中的列表框 (lbLine)。我是 运行 一个单独的线程,它解码从套接字接收到的数据并将它们填充到列表框控件上。 我的代码示例如下:

private void AddLine(ref int nLine, ref int nType)
        {
            PLine pLine = new PLine();
            pLine.LineNo = nLine;
            pLine.Type = nType; 
            ((MainWindow)System.Windows.Application.Current.MainWindow).pConnect.lbLine.Dispatcher.Invoke(() =>
            {
                Dictionary<string, PConn> pConnList =
                          ((MainWindow)System.Windows.Application.Current.MainWindow).PConnList;

                if (((MainWindow)System.Windows.Application.Current.MainWindow).pConnect != null)
                {
                    bool isPCUExist = pConnList.ContainsKey(((MainWindow)System.Windows.Application.Current.MainWindow).pConnect.tbIPAddress.Text);
                    if (isPCUExist && pConnList[((MainWindow)System.Windows.Application.Current.MainWindow).pcuConnect.tbIPAddress.Text].IsConnected)
                    {
                        PConn pConn = pConnList[((MainWindow)System.Windows.Application.Current.MainWindow).pConnect.tbIPAddress.Text];
                        if (pConn != null)
                        {
                            pConn.AddPLineNo(pLine);
                        }
                    }

                }
            });

        }

尝试使用

Application.Current.Dispatcher.Invoke

而不是

(MainWindow)System.Windows.Application.Current.MainWindow).pConnect.lbLine.Dispatcher.Invoke

问题可能是 pConnect 或 lbLine 是一个 UI 对象,因此它与任何其他 UI 对象一样,不能从主线程以外的其他线程使用。

通常只有一个 UI/Main 线程,因此所有调度程序或其他将执行移至该线程的方法都是等效的。