Search code examples
asynchronousf#system.reactivecancellation

What are the possible reasons the finally of an async { try... finally...} is not being called? Rx Involved


I have something like this:

let a =
    async {
        try
            do! Async.AwaitTask someTask
        finally
            // clean up
    }
Async.Start (a, cancellationTokenSource.Token)

When the task being awaited in a finishes, the finally block executes and the clean up is done, but when async a gets cancelled because cancellationTokenSource gets Cancel invoked, clean up is not being done. In fact, I suspect that a keeps running.

I really don't have a clue, so here goes an initial guess: Nah, I'm really guessless.

Edit

It seems that the problem is in the task that a is awaiting. If someTask is this:

Async.Ignore (Async.AwaitIAsyncResult <| Task.Delay(5000))

then, no problem :) But! if the task is this:

vm.Finished.Select(ignore).FirstAsync().ToTask()

(vm is a view model. Finished an event. Basically, I want a to end either because of a cancelation or because Finished occurred in the vm.)

Then a resists to be cancelled or finally is just skipped I don't know which.


Solution

  • You need to pass the CancellationToken to ToTask() otherwise it cannot be canceled.

    Use this ToTask overload.