Fsharpx Async.AwaitObservable不会调用取消延续

时间:2015-01-31 09:40:17

标签: asynchronous f# system.reactive f#-async

我正在尝试在使用Async.AwaitObservable启动的异步工作流程中使用Fsharpx'Async.StartWithContinuations。出于某种原因,如果用于启动此工作流的取消令牌在等待可观察时被取消(但在工作流的其他部分期间不被取消),则永远不会调用取消继续。但是,如果我把它放在use! __ = Async.OnCancel (interruption)内,那么就会调用中断函数。有人可以澄清为什么会发生这种情况以及最好的方法是做什么,并确保其中一个延续函数总是被调用?

open System
open System.Reactive.Linq
open FSharp.Control.Observable
open System.Threading

[<EntryPoint>]
let main _ =
    let cancellationCapability = new CancellationTokenSource()

    let tick = Observable.Interval(TimeSpan.FromSeconds 1.0)
    let test = async {
        let! __ = Async.AwaitObservable tick
        printfn "Got a thing." }

    Async.StartWithContinuations(test,
        (fun () -> printfn "Finished"),
        (fun exn -> printfn "Error!"),
        (fun exn -> printfn "Canceled!"),
        cancellationCapability.Token)

    Thread.Sleep 100
    printfn "Cancelling..."
    cancellationCapability.Cancel()

    Console.ReadLine() |> ignore
    0 // return an integer exit code

2 个答案:

答案 0 :(得分:2)

在我看来,它是如何实现AwaitObservable的一个问题。祝你好运。

也就是说,您可以在客户端代码上使用的一种解决方法是将AwaitObservable包装在任务中:

async {
    let! ct = Async.CancellationToken
    let! __ = 
        Async.StartAsTask(Async.AwaitObservable tick, cancellationToken = ct)
        |> Async.AwaitTask
    printfn "Got a thing." 
}

不理想,但有效。

答案 1 :(得分:2)

似乎GitHub上的Fsharpx版本已经包含一个修复程序(我没有实现)。但是,NuGet(1.8.41)上的当前版本尚未更新以包含此修复程序。请参阅更改here

编辑1 : GitHub上的代码也存在一些带有重放语义的Observables问题。我现在已经解决了这个问题,但希望有一个更清洁的解决方案。在考虑是否有办法使其更简单之后,我会提交PR。

/// Creates an asynchronous workflow that will be resumed when the 
/// specified observables produces a value. The workflow will return 
/// the value produced by the observable.
static member AwaitObservable(observable : IObservable<'T1>) =
    let removeObj : IDisposable option ref = ref None
    let removeLock = new obj()
    let setRemover r = 
        lock removeLock (fun () -> removeObj := Some r)
    let remove() =
        lock removeLock (fun () ->
            match !removeObj with
            | Some d -> removeObj := None
                        d.Dispose()
            | None   -> ())
    synchronize (fun f ->
    let workflow =
        Async.FromContinuations((fun (cont,econt,ccont) ->
            let rec finish cont value =
                remove()
                f (fun () -> cont value)
            setRemover <|
                observable.Subscribe
                    ({ new IObserver<_> with
                        member x.OnNext(v) = finish cont v
                        member x.OnError(e) = finish econt e
                        member x.OnCompleted() =
                            let msg = "Cancelling the workflow, because the Observable awaited using AwaitObservable has completed."
                            finish ccont (new System.OperationCanceledException(msg)) })
            () ))
    async {
        let! cToken = Async.CancellationToken
        let token : CancellationToken = cToken
        #if NET40
        use registration = token.Register(fun () -> remove())
        #else
        use registration = token.Register((fun _ -> remove()), null)
        #endif
        return! workflow
    })

    static member AwaitObservable(observable : IObservable<'T1>) =
        let synchronize f = 
            let ctx = System.Threading.SynchronizationContext.Current 
            f (fun g ->
                let nctx = System.Threading.SynchronizationContext.Current 
                if ctx <> null && ctx <> nctx then ctx.Post((fun _ -> g()), null)
                else g() )

        let continued = ref false
        let continuedLock = new obj()
        let removeObj : IDisposable option ref = ref None
        let removeLock = new obj()
        let setRemover r = 
            lock removeLock (fun () ->  removeObj := Some r)
        let remove() =
            lock removeLock (fun () ->
                match !removeObj with
                | Some d -> 
                    removeObj := None
                    d.Dispose()
                | None   -> ())
        synchronize (fun f ->
        let workflow =
            Async.FromContinuations((fun (cont,econt,ccont) ->
                let rec finish cont value =
                    remove()
                    f (fun () -> lock continuedLock (fun () ->
                        if not !continued then
                            cont value
                            continued := true))
                let observer = 
                    observable.Subscribe
                        ({ new IObserver<_> with
                            member __.OnNext(v) = finish cont v
                            member __.OnError(e) = finish econt e
                            member __.OnCompleted() =
                                let msg = "Cancelling the workflow, because the Observable awaited using AwaitObservable has completed."
                                finish ccont (new System.OperationCanceledException(msg)) })
                lock continuedLock (fun () -> if not !continued then setRemover observer else observer.Dispose())
                () ))
        async {
            let! cToken = Async.CancellationToken
            let token : CancellationToken = cToken
            use __ = token.Register((fun _ -> remove()), null)
            return! workflow
        })

编辑2 : Neater修复了热的可观察问题......

let AwaitObservable(observable : IObservable<'T>) = async {
    let! token = Async.CancellationToken // capture the current cancellation token
    return! Async.FromContinuations(fun (cont, econt, ccont) ->
        // start a new mailbox processor which will await the result
        Agent.Start((fun (mailbox : Agent<Choice<'T, exn, OperationCanceledException>>) ->
            async {
                // register a callback with the cancellation token which posts a cancellation message
                #if NET40
                use __ = token.Register((fun _ ->
                    mailbox.Post (Choice3Of3 (new OperationCanceledException("The opeartion was cancelled.")))))
                #else
                use __ = token.Register((fun _ ->
                    mailbox.Post (Choice3Of3 (new OperationCanceledException("The opeartion was cancelled.")))), null)
                #endif

                // subscribe to the observable: if an error occurs post an error message and post the result otherwise
                use __ = 
                    observable.FirstAsync()
                        .Catch(fun exn -> mailbox.Post(Choice2Of3 exn) ; Observable.Empty())
                        .Subscribe(fun result -> mailbox.Post(Choice1Of3 result))

                // wait for the first of these messages and call the appropriate continuation function
                let! message = mailbox.Receive()
                match message with
                | Choice1Of3 reply -> cont reply
                | Choice2Of3 exn -> econt exn
                | Choice3Of3 exn -> ccont exn })) |> ignore) }