Friday 15 February 2013

c# - Implementing a timeout on a function returning a value -


I have a function that requests a read or write on the serial port and then returns the value that reads I went. I am using the Commstudio Express (I am implementing a class from Commstudio), but this time-out facilities do not work at all, so I am trying to finish my time, I currently have a timer that Port is set to request to read or write, and if the timer stops, the callback closes the connection due to an exception. I tried to throw an exception to the callback of the timer, but the exception is required to be promoted through a thread that calls the original reading / writing function, so it works in this way, but I think it Messy and there is a better way for me to do what I want to do.

Here's a common solution that allows you to wrap any time in the range: < / P>

This uses a useful overload which manually accepts timeout in milliseconds instead of using the timer. The only thing I do in a different way is to swap the flag of success and swap the result value to match the pattern:

  Public stable t performance & lt; T & gt; (Fax & lt; T & gt; func, int timeout) {T result; TryExecute (funk, timeout, outcome); Return result; } Public Static Bull TEEX Activated & lt; T & gt; (Fax  Funk, Int Timeout, Out T Result) {var t = Default (T); Var thread = new thread ((=) gt> t = func ()); Thread.Start (); Var full = thread .join (timeout); If (! Full) thread Assistant (); Results = T; Return complete; }  

And this is how you will use it:

  var func = new Func & lt; String & gt; (() => {Thread. Sleep (200); return "success";}); String result; Debug. TryExecute (Funk, 100, Out Results); Debug Asset (Results == Free); Debug Asset (TryExecute (Function, 300, Outcome Results); Debug Asset (Results == "Success") ;  

You can also add that surcharge which wants to execute a method that does not return the value.


No comments:

Post a Comment