bradgonesurfing
bradgonesurfing

Reputation: 32192

Timing out a task using await in .NET 4.5

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

Await Task.Run( Sub() PerformSomeAction() )

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?

EDIT

I have the following prototype solution

    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

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??

    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

and withing PerformSomeAction I throw SomeTimeoutException if I get the detect the cancelation token.

Upvotes: 0

Views: 1722

Answers (1)

svick
svick

Reputation: 244878

Tasks support cooperative cancellation, that means if you want to cancel a Task that's already running, the code inside the Task has to support cancellation and it decides when will it be canceled. The way to achieve this is to pass the cancellation token to the method and call ThrowIfCancellationRequested() at suitable places in the code of that method.

If the code in the Task doesn't support cancellation, there is no clean way to cancel or abort it.

Upvotes: 2

Related Questions