Sdílet prostřednictvím


Async.catch, <'T> Metoda (F#)

Vytvoří asynchronní výpočtu, který spustí zadaný výpočtu.Pokud tento výpočet úspěšně dokončena, je tato metoda vrátí Choice1Of2 s vrácenou hodnotu.Pokud tento výpočet vyvolá výjimku před dokončením pak návrat Choice2Of2 s výjimkou zvýšené.

Cesta k oboru názvů nebo modul: Microsoft.FSharp.Control

Sestavení: FSharp.Core (v FSharp.Core.dll)

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

// Usage:
Async.Catch (computation)

Parametry

  • computation
    Typ: asynchronní<'T>

    Vstupní výpočtu, který vrací typ "T.

Vrácená hodnota

Výpočet, který vrací volby z t nebo výjimku.

Příklad

Následující příklad kódu ukazuje, jak použít Async.Catch spuštění asynchronního výpočtu, která může vyvolat výjimku.

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)

Platformy

Windows 8, Windows 7, Windows Server 2012 Windows Server 2008 R2

Informace o verzi

F# základní verze knihovny

Podporovány: 2.0, 4.0, přenosné

Viz také

Referenční dokumentace

Třída Control.Async (F#)

Obor názvů Microsoft.FSharp.Control (F#)