使用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 代码的用途有限。