I have a serial port device which I can get certain information from it, for example a voltage.
My problem lies with threading and the end programmer using my events to display the info given to them via the events they subscribe to.
I have a public interface which inheirts from my class that actually does the reading from the serial port.
This base class has a method that is called each time a voltage is read from the serial port.
This is done via a thread that just polls the serial port checking for voltage data.
My thread function in a simple form looks like this:
public void TaskFunction()
{
if(IsVoltageData)
{
OnVolts();
}
}
The OnVolts function looks like this:
protected override void OnVolts()
{
VoltmeterHandler voltsdata = OnVoltsData;
if (voltsdata != null)
{
voltsdata.Invoke(this, new VoltmeterArgs(GetVoltage()));
}
}
The end programmer will use my public interface which has the following Event Arguments, delegate, and event:
public class VoltmeterArgs : EventArgs
{
public double m_Data;
public VoltmeterArgs(double data)
{
m_Data = data;
}
}
public delegate void VoltmeterHandler(object sender, VoltmeterArgs e);
public event VoltmeterHandler OnVoltsData;
Now that end programmer would hook up to that event (OnVoltsData) and use it for example to display the voltage to the user via a textbox or something. Here lies my problem. When ever I do this in my test app:
public void VoltMeter_OnVoltsData(object sender, VoltmeterArgs e)
{
txtVoltage.Text = e.m_Data.ToString();
}
I still get this error:
"Cross-thread operation not valid: Control 'txtVoltage' accessed from a thread other than the thread it was created on."
I guess I am missing something or don't understand something. I thought when you invoked the event it would then fire the event
on the thread it was created on.
Any ideas, options, links, information I can read to help sort this issue I am having out?