I am writing a custom Ref Class with C++ 2005 to control a measurement instrument via Serial Port.
My class inherets System::IO::Ports::SerialPort.
I also define events inside my class to generate action on specific RS232 messaages.
My problem is as follows: Inside the datareceived event handler, I raise events based on messages reveived. However, when my class is instantiated on a windows form, if the event handler defined on the form changes properties of a textbox control, the sytem generates "System.InvalidOperation Exception" and goes on to describe that a different thread tried to access the control.
I can solve the problem by setting the CheckForIllegalCrossThreadCalls property of the Windows Form to false. I do not like this solution, because it seems unsafe, and if someone other than myself was using my class, it might produce unexpected results in their program.
I can also solve the problem using the invoke method of the form / control with delegates to produce a thread safe call as described here:
http://msdn.microsoft.com/msdnmag/issues/04/02/TimersinNET/default.aspxI do not like this solution, as it puts too much burden on the Application programmer using my class, defeating the point of object encapsulation. If my class is in a published Assembly, I will have to explain to the programmer using it to define delegate / use the form->invoke method.
My class also has a System::Timers::Timer ,and the Elapsed event had the same issue, until I set the SynchronizingObject property of the timer to the Windows Form which instantiated my class.
I like this solution, because it doesnt require anycode on the containing form, but the serialport class does not have a SynchronizingObject property, so I fail to see how to produce the same effect.
1 - Can I have my class inheret something so that it has a SychronizingObject Property
2 - Can I use any object System.Threading to invoke the event on the thread of the containing form This is acceptable to me as long as the code required can be part of my class, and not the form on which the class is instantiated.
3 - Any other possible solution I am missing
Thank You