Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Normally TPL code supporting timeout does so through CancellationToken(Source) as mentioned by @outcoldman and @StephenCleary. However, in your scenario you said you wanted the timeout path to also return a string, just a different one.</p> <p>Because of that, instead of using CancellationToken(Source), it will probably be simpler just to treat your timeout code as another task that produces a string and then pick whichever task (timeout task or 'real' task) finishes first and return that string.</p> <p>I changed your DoLongRunningProcess (the innermost function) to be async and returning Task(Of String) just so you wouldn't have to Task.Run it.</p> <p>The 'Await Await' might look odd, but Task.WhenAny returns a Task(Of Task(Of T)) so the first Await is to get to the particular Task that finished first, and then we Await that in order to get the actual string result.</p> <pre><code>Sub Main MainAsync().Wait() End Sub ' Define other methods and classes here Public Async Function MainAsync As Task Dim asyncHandler = New AsyncHandler Await asyncHandler.ProcessRequestAsync(System.Web.HttpContext.Current) Console.WriteLine(asyncHandler.Result) End Function Public Class AsyncHandler Inherits HttpTaskAsyncHandler Public Property Timeout As TimeSpan = TimeSpan.FromSeconds(10) Public Property Result As String Public Overrides Async Function ProcessRequestAsync(context As HttpContext) As Task Me.Result = Await DoLongRunningProcessAsync(context) End Function Private Async Function DoLongRunningProcessAsync(context As HttpContext) As Task(Of String) 'TODO: add a timeout so that if this takes too long we return "timeout": Dim workerTask As Task(Of String) = DoLongRunningProcess(context) Dim cancelTask As Task(Of String) = DoTimeout() Return Await Await Task.WhenAny(workerTask, cancelTask) End Function Private Async Function DoTimeout() As Task(Of String) Await Task.Delay(Timeout) Return "timeout" End Function Private Async Function DoLongRunningProcess(context As HttpContext) As Task(Of String) 'perform long running process.... Await Task.Delay(TimeSpan.FromSeconds(15)) Return "success" End Function End Class </code></pre>
    singulars
    1. This table or related slice is empty.
    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. 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