I have a function that calls out a read or write request on a serial port and then returns the value that was read. I am using Commstudio express (I'm implementing a class from Commstudio) , but it's timeout features don't appear to work at all, so I'm trying to implement my own timeout. Currently I have a timer that is set upon request to read or write to the port, and if the timer goes off, the callback closes the connection causing an exception. I tried to have the callback of the timer throw an exception, but the exception needs to be propagated up through the thread that was calling the original read/write function, so in this way, it works, but I feel like it's messy and there must be a better way to do what I want.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Sounds like you're doing a blocking read/write. What you want to do is a non-blocking read/write.
There is probably a way to tell the com port that you're wanting non- blocking.
Are you sure the timeouts are not working with commstudio? maybe you have to do something special to initialise them.
In any case, you want to read as much data as possible and if none is available time out (depending on what the value of the time out is). You'll want to keep looping while no data available and no error and then return a time out condition if there wasn't anything available.
Make your read function return an integer. negative values = error value e.g. -1 = timeout, positive number of bytes read... at least thats the way I'd do it.
For the comport you could just test if there is anything available and then do a read instead of doing a blocking read without knowing there is something yet. Something like:
In case someone wants to do this in VB.Net, don't listen to those who say it can't be done! You may need to alter your generic parameters to suit your use case.
And an example of how to use it (mine was with
Regex.Match
, which sometimes goes off into never never land if the patterns contains too many wild cards:Here is a generic solution that allows you to wrap any method in a timeout:
http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/
It uses the useful Thread.Join overload that accepts a timeout in milliseconds rather than manually using timers. The only thing I would do differently is swap the success flag and result value to match the TryParse pattern, as follows:
And this is how you would use it:
You could also add overloads that accept Action instead of Func if you want to execute a method that doesn't return a value.