Async.Catch<'T> 方法 (F#)

更新:2010 年 8 月

创建执行指定计算的异步计算。 如果此计算成功完成,则此方法返回包含返回值的 Choice1Of2。 如果此计算在完成之前引发异常,则返回包含引发的异常的 Choice2Of2。

命名空间/模块路径: Microsoft.FSharp.Control

程序集:FSharp.Core(在 FSharp.Core.dll 中)

// Signature:
static member Catch : Async<'T> -> Async<Choice<'T,exn>>

// Usage:
Async.Catch (computation)

参数

  • computation
    类型:Async<'T>

    返回类型 'T 的输入计算。

返回值

返回类型为 T 或异常 选项 的计算。

示例

以下代码示例演示如何使用 Async.Catch 运行可能引发异常的异步计算。

open System
open System.IO

let writeToFile filename numBytes = 
    async {
        use file = File.Create(filename)
        printfn "Writing to file %s." filename
        do! file.AsyncWrite(Array.zeroCreate<byte> numBytes)
    }

let readFile filename numBytes =
    async {
        use file = File.OpenRead(filename)
        printfn "Reading from file %s." filename
        do! file.AsyncRead(numBytes) |> Async.Ignore
    }

let filename = "BigFile.dat"
let numBytes = 100000000

let result1 = writeToFile filename numBytes
             |> Async.Catch
             |> Async.RunSynchronously
match result1 with
| Choice1Of2 _ -> printfn "Successfully wrote to file."; ()
| Choice2Of2 exn -> 
      printfn "Exception occurred writing to file %s: %s" filename exn.Message

// Start these next two operations asynchronously, forcing an exception due
// to trying to access the file twice simultaneously.
Async.Start(readFile filename numBytes)
let result2 = writeToFile filename numBytes
             |> Async.Catch
             |> Async.RunSynchronously
match result2 with
| Choice1Of2 buffer -> printfn "Successfully read from file."
| Choice2Of2 exn ->
    printfn "Exception occurred reading from file %s: %s" filename (exn.Message)

平台

Windows 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2

版本信息

F# 运行时

受以下版本支持:2.0、4.0

Silverlight

受以下版本支持:3

请参见

参考

Control.Async 类 (F#)

Microsoft.FSharp.Control 命名空间 (F#)

修订记录

Date

修订记录

原因

2010 年 8 月

添加了代码示例。

信息补充。