I’ve got a little stuck with a small problem here:
I use serialport communications – all my functions for comm. are wrapped into my own serialport class.
Instances of that class are supposed to only be used in the
using(Serport port = new Serport(...)){}
to assure, that Dispose() is called after the operation.
Now this is no problem with one time calls, but I can’t think of a way for this:
I have a function that is supposed to be called via a while loop for permanently refreshing via comport until the user interrupts (the function is designed to reset a timer itself every time it’s called and time out when not called anymore).
Now this operation is quite time-critical and cannot be opening and closing the serialport every time it gets called. So using the using pattern from up there inside that function won’t work ( or will it ?)
The only way to realize this I can think of is to place the using(){} around the while loop – I’d like to avoid that though since it would mix up my code that is clearly built in a way, that comport access is handled low level and to the real app only simple functions that do all the work are availible…
Do you guys see any alternative? Is there a way to terminate the using pattern by hand? Just calling Dispose() by hand in my timeout-timer won’t work since it won’t be called if I get an exception – and I have to be sure that Dispose() gets called, so the serialport stay manageable…
Thanks for your help!!
You don’t need to use a
usingstatement for an IDisposable:From MSDN:
You can either make sure that your exception handling does call Dispose, or you can for example make some outer Parent class inherit from IDisposable:
and wrap the creation of the Parent object in the
usingstatement, and let it worry about calling Dispose on the Serport.