Click to See Complete Forum and Search --> : System.Invalidoperation - Timer and Serialport Class


rognorak
January 22nd, 2007, 04:06 PM
I am writing a class that inherets "public System::IO::Ports::SerialPort"
I also have 2 timers instantiated inside the class of type "System::Timers::Timer^"

I define a custom event / delegate pair, and every time i try to raise my event from within a timer event handler or the serialport class DataReceived event handler, the application generates an exception of:

System.Invalidoperation exception

this seems to be because the timer elapsed event and the serialport Datareceived Event are operating on seperate threads from the main application.

I was able to aleviate the problem with the timer object by setting the "SynchronizingObject" property of the timers to a handle to the form on which my top level class is instantiated.

However, the SerialPort class does not have this property.

Any Idea how to aleviate this problem for the serial port events? Research indicates using the Forms->invoke() method of the form on which my top level object is instantiated - but I do not know how to do this

Thank You

cilu
January 23rd, 2007, 09:41 AM
There is this discusion in the C++ forum about private inheritance, want what IMPLEMENTED-IN-TERMS-OF mean.

http://www.codeguru.com/forum/showthread.php?t=412309

I think your example is a very good one for the point that inheritance is overused. You did no explain too much what this derived class of SerialPort is, but I got the feeling this does not have an IS-A relashionship with the SerialPort, i.e. your derived class it not a SerialPort. More likely, it is IMPLEMENTED-IN-TERMS-OF a serial port, since you need to send and receive data on a communication channel. That rather means you should use aggregation not inheritance.

If you share more information about this class it would be great, otherwise I would just play guessing.

rognorak
January 23rd, 2007, 01:40 PM
You are correct, I do not need inheritance, I could have just instantiated a serialport object inside my class and used it. I'm not overriding anything.

However - this does not effect my threading problem. I thought for a second that if I changed around what I'd done to eliminate the inheritance, I could use delegates in my top level class to raise the events on the containing forms thread, but my custom class would not have an invoke method, so I do not think this will help.