Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>Older solution, not feasible for tasks that are not cancellation-aware</h3> <p>You should pass a <code>CancellationToken</code>:</p> <pre><code>private async Task DownloadFile() { WebClient client = new WebClient(); using(var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)) { var downloadTask = Task.Run( () =&gt; client.DownloadFile("http://www.worldofcats.com/bigkitty.zip", "c:\\cats\\"), cts.Token ); await downloadTask; } } </code></pre> <p>Now when you <code>await DownloadFile()</code> you can wrap it in a <code>try/catch</code> block to catch the <code>TaskCanceledException</code> (or <a href="https://stackoverflow.com/a/13040503/1180426"><code>OperationCanceledException</code></a>):</p> <pre><code>try { await DownloadFile(); } catch(TaskCanceledException) { //Timeout! } </code></pre> <h3>[EDIT]</h3> <p>As was noticed in comments, you can't cancel a task that's not cancellation-aware - somehow I forgot about that (boo!). But no worries, you can fix that by using <a href="http://msdn.microsoft.com/en-US/library/hh193917.aspx" rel="nofollow noreferrer"><code>DownloadFileTaskAsync</code></a> and <a href="http://msdn.microsoft.com/en-US/library/system.net.webclient.cancelasync.aspx" rel="nofollow noreferrer"><code>CancelAsync</code></a>, so you don't even need cancellation token:</p> <pre><code>var downloadTask = client.DownloadFileTaskAsync("http://www.worldofcats.com/bigkitty.zip", "c:\\cats\\"); var timerTask = Task.Delay(TimeSpan.FromSeconds(60)); await Task.WhenAny(downloadTask, timerTask); client.CancelAsync(); // This does nothing if there's no operation in progress, as noted in documentation </code></pre>
 

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