-
May 5th, 2011, 06:32 PM
#1
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";
}
-
May 5th, 2011, 06:39 PM
#2
Re: Cross Thread Exception
You're on the right track.
-
May 9th, 2011, 07:40 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|