Async.Await未捕获任务异常 [英] Async.Await not catching Task exception

查看:355
本文介绍了Async.Await未捕获任务异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不返回任何内容的任务。您无法在此类任务上执行Async.AwaitTask,因此您需要执行Async.AwaitIAsyncTask。不幸的是,这似乎吞没了底层Task抛出的所有异常:-

  TaskFactory()。StartNew(Action(fun _ -> failwith oops))
|> Async.AwaitIAsyncResult
|>异步忽略
|> Async.RunSynchronously

// val:unit =()

打开另一方面,AwaitTask正确地级联了该异常:-

  TaskFactory()。StartNew(fun _-> failwith oops 
5)
|> Async.AwaitTask
|>异步忽略
|> Async.RunSynchronously

// POP!

将常规(非通用)任务视为异步但仍能传播异常的最佳方法是什么?

解决方案

来自 Xamarin F#衬衫应用程序(我最初从戴夫·托马斯那里借来的):

> [< AutoOpen>]
模块Async =
让内联awaitPlainTask(task:Task)=
//如果出错$ b $,则从先前任务中抛出异常b让continuation(t:Task)=如果t.IsFaulted然后引发t.Exception
task.ContinueWithcontinuation |> Async.AwaitTask


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 = ()

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?

解决方案

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未捕获任务异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆