问题描述
我有一个不返回任何内容的任务.您不能对此类任务执行 Async.AwaitTask,因此您需要执行 Async.AwaitIAsyncTask.不幸的是,这似乎只是吞下了基础任务抛出的任何异常:-
I have a Task that does not return anything. You can't do an Async.AwaitTask on such a Task, so you need to do an Async.AwaitIAsyncTask instead. Unfortunately this seems to just swallow any exceptions that the underlying Task throws out: -
TaskFactory().StartNew(Action(fun _ -> failwith "oops"))
|> Async.AwaitIAsyncResult
|> Async.Ignore
|> Async.RunSynchronously
// val it : unit = ()
另一方面,AwaitTask 正确地级联异常:-
On the other hand, AwaitTask correctly cascades the exception: -
TaskFactory().StartNew(fun _ -> failwith "oops"
5)
|> Async.AwaitTask
|> Async.Ignore
|> Async.RunSynchronously
// POP!
将常规(非通用)任务视为异步但仍会传播异常的最佳方法是什么?
What's the best way of treating regular (non-generic) Tasks as Async yet still get propagation of exceptions?
推荐答案
来自 Xamarin F# Shirt App(我最初是从 Dave Thomas 那里借来的):
From the Xamarin F# Shirt App (which I originally borrowed from Dave Thomas):
[<AutoOpen>]
module Async =
let inline awaitPlainTask (task: Task) =
// rethrow exception from preceding task if it faulted
let continuation (t : Task) = if t.IsFaulted then raise t.Exception
task.ContinueWith continuation |> Async.AwaitTask
这篇关于Async.Await 未捕获任务异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!