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 の Choice または例外を返す計算。

使用例

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#)

履歴の変更

日付

履歴

理由

2010 年 8 月

コード例を追加。

情報の拡充