CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2010
    Posts
    56

    Cross Thread Exception

    Im having issues with cross thread exceptions, basically I have an event hooked to a method that updates a textbox if I receive data from my serial port which has an Arduino. The problem is that I get the cross thread exception.

    Now I managed to solve this before with some Google searches and cannibalizing code but that only worked with a method that took in a string. Now I have a method that has a matching delegate.

    Problem is I don't know if I am on the right track here, below is my improvised code any help would be appreciated.

    Code:
            private void ReceiveMessage(object sender, SerialDataReceivedEventArgs e) 
            {
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadExisting();
                string data = "";
    
                if (InvokeRequired)
                {
                    this.Invoke(new Action<object, EventArgs>(ReceiveMessage), new object[] { e });
                    return;
                }
                outputTxtB.Text += indata + "\r\n";
            }

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Cross Thread Exception

    You're on the right track.

  3. #3
    Join Date
    Jun 2010
    Posts
    56

    Re: Cross Thread Exception

    Got it. Although I had to put a try in there just in case I close the program when I am still reading from the serial port not a big problem for this project.

    Now to go fix some of the Arduino code which is in C.


    Code:
            private void ReceiveMessage(object sender, SerialDataReceivedEventArgs e) 
            {
                
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadExisting();
    
                if (InvokeRequired)
                {
                    //This try is in place because quitting the program while the port is being read
                    //leads to an exception I think, well something leads to an exception if you quit while its being read.
                    try
                    {
                        this.Invoke(new MethodInvoker(delegate
                        {
                            serialInputTb.Text += indata;
                        }));
                        return;
                    }
                    catch { }
                }
                else
                {
                    serialOutputTb.Text += indata;
                }
            }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured