共用方式為


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

建立會執行指定計算的非同步計算。如果這個計算順利完成,這個方法會將 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 8 中, Windows 7, Windows Server 2012 上, Windows Server 2008 R2

版本資訊

F# 核心程式庫版本

支援版本:2.0, 4.0,可攜式執行檔 (PE)。

請參閱

參考

Control.Async 類別 (F#)

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