0

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

                }
            });

        }

Ejob
  • 1
  • 2
  • 2
    What exception is it throwing, and at what point in the code? – Jasper Kent Mar 25 '20 at 15:05
  • Consider to capture `((MainWindow)System.Windows.Application.Current.MainWindow)` once. – Sinatr Mar 25 '20 at 15:08
  • @JasperKent: Exception at calling the Dispatcher " `((MainWindow)System.Windows.Application.Current.MainWindow).pConnect.lbLine.Dispatcher.Invoke(() =>` and the exception is _The calling thread cannot access this object because a different thread owns it_ – Ejob Mar 25 '20 at 15:12
  • @Sinatr I tried it before, but didnt work out. – Ejob Mar 25 '20 at 15:17

1 Answers1

1

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Thanks a lot. I didnt get the exception now.. However I ll check if my list box gets updated or not. – Ejob Mar 25 '20 at 15:40