Condividi tramite


Metodo Async.Catch<'T> (F#)

Consente di creare un calcolo asincrono che esegue un calcolo specificato. Se il calcolo viene completato senza errori, questo metodo restituisce Choice1Of2 con il valore restituito. Se il calcolo genera un'eccezione prima del completamento, restituisce Choice2Of2 con l'eccezione generata.

Percorso di spazio dei nomi/modulo: Microsoft.FSharp.Control

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

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

// Usage:
Async.Catch (computation)

Parametri

  • computation
    Tipo: Async<'T>

    Calcolo di input che restituisce il tipo 'T.

Valore restituito

Calcolo che restituisce una Scelta di tipo 'T o un'eccezione.

Esempio

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare Async.Catch per eseguire un calcolo asincrono che potrebbe generare un'eccezione.

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)

Piattaforme

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

Informazioni sulla versione

F# Runtime

Supportato in: 2.0, 4.0

Silverlight

Supportato in: 3

Vedere anche

Riferimenti

Classe Control.Async (F#)

Spazio dei nomi Microsoft.FSharp.Control (F#)

Cronologia delle modifiche

Data

Cronologia

Motivo

Agosto 2010

Aggiunto esempio di codice.

Miglioramento delle informazioni.