Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Some minor changes to Pop Catalin's great answer:</p> <ul> <li>Func instead of Action</li> <li>Throw exception on bad timeout value</li> <li>Calling EndInvoke in case of timeout</li> </ul> <p>Overloads have been added to support signaling worker to cancel execution:</p> <pre><code>public static T Invoke&lt;T&gt; (Func&lt;CancelEventArgs, T&gt; function, TimeSpan timeout) { if (timeout.TotalMilliseconds &lt;= 0) throw new ArgumentOutOfRangeException ("timeout"); CancelEventArgs args = new CancelEventArgs (false); IAsyncResult functionResult = function.BeginInvoke (args, null, null); WaitHandle waitHandle = functionResult.AsyncWaitHandle; if (!waitHandle.WaitOne (timeout)) { args.Cancel = true; // flag to worker that it should cancel! /* •————————————————————————————————————————————————————————————————————————• | IMPORTANT: Always call EndInvoke to complete your asynchronous call. | | http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx | | (even though we arn't interested in the result) | •————————————————————————————————————————————————————————————————————————• */ ThreadPool.UnsafeRegisterWaitForSingleObject (waitHandle, (state, timedOut) =&gt; function.EndInvoke (functionResult), null, -1, true); throw new TimeoutException (); } else return function.EndInvoke (functionResult); } public static T Invoke&lt;T&gt; (Func&lt;T&gt; function, TimeSpan timeout) { return Invoke (args =&gt; function (), timeout); // ignore CancelEventArgs } public static void Invoke (Action&lt;CancelEventArgs&gt; action, TimeSpan timeout) { Invoke&lt;int&gt; (args =&gt; { // pass a function that returns 0 &amp; ignore result action (args); return 0; }, timeout); } public static void TryInvoke (Action action, TimeSpan timeout) { Invoke (args =&gt; action (), timeout); // ignore CancelEventArgs } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload