Condividi tramite


Metodo Async.AwaitEvent<'Del,'T> (F#)

Crea un calcolo asincrono che attende una singola chiamata di un evento CLI aggiungendo un gestore all'evento. Una volta completato o annullato il calcolo, il gestore viene rimosso dall'evento.

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

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

// Signature:
static member AwaitEvent : IEvent<'Del,'T> * ?(unit -> unit) -> Async<'T> (requires delegate)

// Usage:
Async.AwaitEvent (event)
Async.AwaitEvent (event, cancelAction = cancelAction)

Parametri

  • event
    Tipo: IEvent<'Del,'T>

    Evento da gestire una volta.

  • cancelAction
    Tipo: (unit -> unit)

    Funzione facoltativa per eseguire un'operazione anziché annullarla quando viene emesso un annullamento.

Valore restituito

Calcolo asincrono che attende la chiamata dell'evento.

Note

Il calcolo risponderà all'annullamento mentre attende l'evento. Se si verifica un annullamento e viene specificato cancelAction, tale azione verrà eseguita e il calcolo continuerà ad attendere l'evento. Se cancelAction non viene specificato, l'annullamento determina l'annullamento immediato del calcolo.

Esempio

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare Async.AwaitEvent per impostare un'operazione su file eseguita in risposta a un evento che indica che il file è stato modificato. In questo caso, l'attesa del termine dell'evento impedisce di tentare di accedere al file mentre è bloccato.

open System.Windows.Forms
open System.IO

let filename = "longoutput.dat"
if File.Exists(filename) then
    File.Delete(filename)
let watcher = new FileSystemWatcher(Path = Directory.GetCurrentDirectory(),
                                    NotifyFilter = NotifyFilters.LastWrite,
                                    Filter = filename)
watcher.Changed.Add(fun args -> printfn "The file %s is changed." args.Name)
watcher.EnableRaisingEvents <- true

let testFile = File.CreateText("Test.txt")
testFile.WriteLine("Testing...")
testFile.Close()

let form = new Form(Text = "Test Form")
let buttonSpacing = 5
let button1 = new Button(Text = "Start")
let button2 = new Button(Text = "Start Invalid", Top = button1.Height + buttonSpacing)
let button3 = new Button(Text = "Cancel", Top = 2 * (button1.Height + buttonSpacing))
let label1 = new Label(Text = "", Width = 200, Top = 3 * (button1.Height + buttonSpacing))
let label2 = new Label(Text = "", Width = 200, Top = 4 * (button1.Height + buttonSpacing))
form.Controls.AddRange [| button1; button2; button3; label1 |]
form.Controls.Add(button1)

let bufferData = Array.zeroCreate<byte> 100000000

let async1 filename =
     async {
       printfn "Creating file %s." filename
       use outputFile = File.Create(filename)
       printfn "Attempting to write to file %s." filename
       do! outputFile.AsyncWrite(bufferData) 
     }

let async2 filename =
     async {
       printfn "Waiting for file system watcher notification."
       // If you omit the call to AwaitEvent, an exception is thrown that indicates that the
       // file is locked.
       let! args = Async.AwaitEvent(watcher.Changed)
       printfn "Attempting to open and read file %s." filename
       use inputFile = File.OpenRead(filename)
       let! buffer = inputFile.AsyncRead(100000000)
       printfn "Successfully read file %s." filename
       return buffer
     }   

button1.Click.Add(fun _ ->
                  // Start these as tasks simultaneously.
                  Async.StartAsTask(async1 filename) |> ignore
                  Async.StartAsTask(async2 filename) |> ignore
                  ())
button2.Click.Add(fun _ ->
                  Async.StartAsTask(async1 filename) |> ignore
                  Async.StartAsTask(async2 "longoutputX.dat")  |> ignore
                  ())
Application.Run(form)

Output di esempio

                

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

Luglio 2010

Aggiunto esempio di codice.

Miglioramento delle informazioni.