Share via


Async.Catch<'T>-Methode (F#)

Aktualisiert: August 2010

Erstellt eine asynchrone Berechnung, die eine angegebene Berechnung ausführt. Wenn diese Berechnung erfolgreich abgeschlossen ist, gibt diese Methode Choice1Of2 mit dem zurückgegebenen Wert zurück. Wenn diese Berechnung eine Ausnahme auslöst, bevor sie abgeschlossen ist, wird Choice2Of2 mit der ausgelösten Ausnahme zurückgegeben.

Namespace/Modulpfad: Microsoft.FSharp.Control

Assembly: FSharp.Core (in FSharp.Core.dll)

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

// Usage:
Async.Catch (computation)

Parameter

  • computation
    Typ: Async<'T>

    Die Eingabeberechnung, die den Typ 'T zurückgibt.

Rückgabewert

Eine Berechnung, die eine Auswahl von Typ 'T oder eine Ausnahme zurückgibt.

Beispiel

Im folgenden Codebeispiel wird veranschaulicht, wie mit Async.Catch eine asynchrone Berechnung ausgeführt wird, die möglicherweise eine Ausnahme auslöst.

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)

Plattformen

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

Versionsinformationen

F#-Runtime

Unterstützt in: 2.0, 4.0

Silverlight

Unterstützt in: 3

Siehe auch

Weitere Ressourcen

Control.Async-Klasse (F#)

Microsoft.FSharp.Control-Namespace (F#)

Änderungsprotokoll

Datum

Versionsgeschichte

Grund

August 2010

Codebeispiel hinzugefügt.

Informationsergänzung.