C#:调用线程无法访问此对象,因为其他线程拥有它]]

问题描述 投票:0回答:1

我知道这个问题已经回答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);
                        }
                    }

                }
            });

        }

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

c# wpf multithreading dispatcher
1个回答
0
投票

尝试使用

© www.soinside.com 2019 - 2024. All rights reserved.