统一任务<t>和F#MailboxProcessor异常处理</t>

时间:2012-06-04 12:41:03

标签: f# mailboxprocessor

使用Task&lt; T&gt;时,在Task.Wait()期间抛出任务执行期间的异常;当使用F#的MailBoxProcessor时,异常被吞下,需要按照this question明确处理。

这种差异使得很难通过Task将F#代理暴露给C#代码。例如,此代理:

type internal IncrementMessage = 
    Increment of int * AsyncReplyChannel<int>

type IncrementAgent() =
    let counter = Agent.Start(fun agent -> 
        let rec loop() = async { let! Increment(msg, replyChannel) = agent.Receive()
                                match msg with 
                                | int.MaxValue -> return! failwith "Boom!"
                                | _ as i -> replyChannel.Reply (i + 1)
                                            return! loop() }

        loop())

    member x.PostAndAsyncReply i =
        Async.StartAsTask (counter.PostAndAsyncReply (fun channel -> Increment(i, channel)))

可以从C#调用,但异常不会返回到C#:

[Test]
public void ExceptionHandling()
{
    //
    // TPL exception behaviour
    //
    var task = Task.Factory.StartNew<int>(() => { throw new Exception("Boom!"); });

    try
    {
        task.Wait();
    }
    catch(AggregateException e)
    {
        // Exception available here
        Console.WriteLine("Task failed with {0}", e.InnerException.Message);
    }

    //
    // F# MailboxProcessor exception behaviour
    //
    var incAgent = new IncrementAgent();
    task = incAgent.PostAndAsyncReply(int.MaxValue);

    try
    {
        task.Wait(); // deadlock here
    }
    catch (AggregateException e)
    {
        Console.WriteLine("Agent failed with {0}", e.InnerException.Message);
    }
}

C#代码只挂起在task.Wait()上,而不是获得异常。有没有办法让F#代理行为像任务?如果没有,似乎将F#代理暴露给其他.NET代码的用途有限。

1 个答案:

答案 0 :(得分:3)

处理它的一种方法是让代理返回带有错误情况的DU。然后,您可以从代理外部提出异常。

type internal IncrementResponse =
    | Response of int
    | Error of exn

type internal IncrementMessage = 
    | Increment of int * AsyncReplyChannel<IncrementResponse>

type IncrementAgent() =
    let counter = Agent.Start(fun agent -> 
        let rec loop() = 
          async { 
            let! Increment(msg, replyChannel) = agent.Receive()
            match msg with 
            | int.MaxValue -> replyChannel.Reply (Error (Failure "Boom!"))
            | _ as i -> replyChannel.Reply (Response(i + 1))
            return! loop() 
          }
        loop())

    member x.PostAndAsyncReply i =
        Async.StartAsTask (
          async {
            let! res = counter.PostAndAsyncReply (fun channel -> Increment(i, channel))
            match res with
            | Response i -> return i
            | Error e -> return (raise e)
          }
        )