Search code examples
c#wpfmultithreadingdispatcher

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


I know this question is already answered before. But I tried in my project and it is throwing exception. I am new to C# and I want to know where am doing wrong. Thanks in advance.

Issue: I am trying to update a list box(lbLine) which is present in a dialog box. I am running a separate thread that decodes the data received from the socket and populates them on the list box control. My code sample is as below:

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

                }
            });

        }


Solution

  • Try using

    Application.Current.Dispatcher.Invoke
    

    instead of

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

    The problem may be that the pConnect or lbLine is a UI object, so it, like any other UI object, cannot be used from other threads than the main thread.

    Usually there is only one UI/Main thread, so all dispatchers or other ways to move execution to it will be equivalent.