已取消的任务不会将控制权返回到异步块

时间:2017-02-08 17:13:43

标签: asynchronous f# task cancellation mailboxprocessor

我试图将此减少到尽可能小的重复,但它仍然有点长,我的道歉。

我有一个F#项目,它使用如下代码引用C#项目。

public static class CSharpClass {
    public static async Task AsyncMethod(CancellationToken cancellationToken) {
        await Task.Delay(3000);
        cancellationToken.ThrowIfCancellationRequested();
    }
}

这是F#代码。

type Message = 
    | Work of CancellationToken
    | Quit of AsyncReplyChannel<unit>

let mkAgent() = MailboxProcessor.Start <| fun inbox -> 
    let rec loop() = async {
        let! msg = inbox.TryReceive(250)
        match msg with
        | Some (Work cancellationToken) ->
            let! result = 
                CSharpClass.AsyncMethod(cancellationToken)
                |> Async.AwaitTask
                |> Async.Catch
            // THIS POINT IS NEVER REACHED AFTER CANCELLATION
            match result with
            | Choice1Of2 _ -> printfn "Success"
            | Choice2Of2 exn -> printfn "Error: %A" exn    
            return! loop()
        | Some (Quit replyChannel) -> replyChannel.Reply()
        | None -> return! loop()
    }
    loop()

[<EntryPoint>]
let main argv = 
    let agent = mkAgent()
    use cts = new CancellationTokenSource()
    agent.Post(Work cts.Token)
    printfn "Press any to cancel."
    System.Console.Read() |> ignore
    cts.Cancel()
    printfn "Cancelled."
    agent.PostAndReply Quit
    printfn "Done."
    System.Console.Read()

问题是,取消后,控制永远不会返回异步块。我不确定它是否挂在AwaitTaskCatch中。 Intuition告诉我它在尝试返回上一个同步上下文时会阻止,但我不确定如何确认这一点。我正在寻找有关如何解决此问题的想法,或者也许有更深入了解的人可以发现问题。

可能的解决方案

let! result = 
    Async.FromContinuations(fun (cont, econt, _) ->
        let ccont e = econt e
        let work = CSharpClass.AsyncMethod(cancellationToken) |> Async.AwaitTask
        Async.StartWithContinuations(work, cont, econt, ccont))
    |> Async.Catch

1 个答案:

答案 0 :(得分:3)

最终导致此行为的原因是取消在F#Async中是特殊的。取消有效地转换为stop and teardown。正如您在source中所看到的,Task中的取消使其完全退出计算。

如果您想要在计算过程中处理好的旧OperationCanceledException,我们可以自己制作。{/ p>

type Async =
    static member AwaitTaskWithCancellations (task: Task<_>) =
        Async.FromContinuations(fun (setResult, setException, setCancelation) ->
            task.ContinueWith(fun (t:Task<_>) -> 
                match t.Status with 
                | TaskStatus.RanToCompletion -> setResult t.Result
                | TaskStatus.Faulted -> setException t.Exception
                | TaskStatus.Canceled -> setException <| OperationCanceledException()
                | _ -> ()
            ) |> ignore
        )

取消现在只是另一个例外 - 我们可以处理异常。 这是复制者:

let tcs = TaskCompletionSource<unit>()
tcs.SetCanceled()

async { 
    try        
        let! result = tcs.Task |> Async.AwaitTaskWithCancellations
        return result
    with
         | :? OperationCanceledException -> 
           printfn "cancelled"      
         | ex -> printfn "faulted %A" ex

    ()
} |> Async.RunSynchronously