Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could use <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" rel="nofollow">Tasks</a> to do this, here's an example:</p> <pre><code>public string AskAPI(string uri, int millis) { using (var task = new Task&lt;string&gt;(() =&gt; api.Query(uri))) { task.Start(); task.Wait(millis); if (!task.IsCompleted) throw new TimeoutException(); return task.Result; } } </code></pre> <p>Thanks to Guillaume for suggesting to use a TimeoutException.</p> <p>But as Jim Mischel points out, this won't stop the task from completing, in which case it'd be best if you could modify the API you're calling because then you could make full use of the CancellationToken class which was made for this kind of thing.</p> <p>Other than that, the only other quick solution I can think of (which may be inadvisable) would be to wrap the method (or combine it) with something like this:</p> <pre><code>public T Await&lt;T&gt;(Func&lt;T&gt; fun, int millis) { using (var cancel = new CancellationTokenSource(millis)) using (var task = new Task&lt;T&gt;(() =&gt; { T result = default(T); var thread = new Thread(() =&gt; result = fun()); thread.Start(); while (!cancel.Token.IsCancellationRequested &amp;&amp; thread.IsAlive) ; // Wait for a sign from above thread.Abort(); cancel.Token.ThrowIfCancellationRequested(); return result; }, cancel.Token)) { task.Start(); task.Wait(millis); cancel.Cancel(); if (!task.IsCompleted) throw new TimeoutException(); return task.Result; } } </code></pre> <p>And then call it using:</p> <pre><code>Await(() =&gt; AskAPI("http://some.uri"), 30000); </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. 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