title: Timing out a task using await in .NET 4.5
body: <p>I'm trying out Async / Await in VB.NET 4.5 and would like my task
  to timeout if it doesn't complete within a certain period. I have</p>
  
  <pre><code>Await Task.Run( Sub() PerformSomeAction() )
  </code></pre>
  
  <p>which seems neat. I also see there is a form of Task.Run that takes a cancellation token. How could I use this to cancel the task in case of some timeout?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have the following prototype solution</p>
  
  <pre><code>    Dim cts = New CancellationTokenSource()
      Dim ct As CancellationToken = cts.Token
      Dim delay = Task.Delay(1000)
      Dim completed = Await Task.WhenAny(Task.Run(Sub() PerfomSomeAction(ct), ct), delay)
      If completed Is delay Then
              cts.Cancel()
      End If
  </code></pre>
  
  <p>This looks quite noisy code. Is this good? Another idea would be to handle
  the timeout as an exception and use cts.CancelAfter. Something like this??</p>
  
  <pre><code>    Dim cts = New CancellationTokenSource()
      Dim ct As CancellationToken = cts.Token
      try
          cts.CancelAfter(1000) 'ms
          Dim completed = Task.Run(Sub() PerformSomeAction(ct), ct)
      catch SomeTimeoutException
      end try
  </code></pre>
  
  <p>and withing PerformSomeAction I throw SomeTimeoutException if I get the
  detect the cancelation token.</p>