5

使用Task<T>时,在Task.Wait()期间抛出任务执行过程中的异常;使用 F# 的 MailBoxProcessor 时,异常被吞没,需要根据这个问题明确处理。

这种差异使得很难通过任务将 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 代码的用途有限。

4

1 回答 1

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)
          }
        )
于 2012-06-04T16:55:47.350 回答