我相信,我的问题是双重问题。在下文中,如何捕获AggregateException
并在
Task
个对象,而不是Task<void>
个?Task<_>
时(例如Task<void>
?这是一个简短的,有些捏造的片段。以下代码段中的taskGenerator
模拟了一些外部C#库函数,该函数返回的数组Tasks
或Task
数组合Task.WhenAll
。
我不确定如何捕获生成的AggregateException
并将其打印在通用或非通用情况下。然后其他问题是我需要转换以满足FSharpx
的非泛型的交互,但然后Ignore
抛出可能不需要的异常。Ignore
函数来自here,我相信这是一种将Task
转换为Task<unit>
的方式。
open FSharpx
open System.Threading.Tasks
open System
open FSharpx.Task
[<EntryPoint>]
let main argv =
let Ignore(task:Task) =
let continuation (t: Task): unit =
if t.IsFaulted then
raise t.Exception
else
()
task.ContinueWith continuation
let taskGenerator() =
let task = TaskBuilder(scheduler = TaskScheduler.Default)
//The following just emulates an external source that returns a bunch of plain
//tasks. It could return also one plain task one would like to await for (e.g.
//this exernal, simulated source could call Task.WhenAll.)
task {
let tasks =
[|1; 2; 3;|]
|> Seq.map(fun i ->
let taskSource = new TaskCompletionSource<unit>()
taskSource.SetException(new ArgumentException("Argh!"))
taskSource.Task :> Task)
return! Task.WhenAll(tasks) |> Ignore
}
let final() =
let task = TaskBuilder(scheduler = TaskScheduler.Default)
task {
let! a = taskGenerator()
a |> ignore
}
try
let finalRes = final()
finalRes |> ignore
with :? AggregateException as aex ->
printfn "%A" aex
let x = System.Console.ReadLine()
0