Compartilhar via


Async.AwaitEvent <'Del ', ' t > Método (F#)

Cria uma computação assíncrona que aguarda uma única invocação de um evento CLI, adicionando um manipulador para o evento. Depois que a computação é concluída ou cancelada, o manipulador é removido do evento.

Caminho do namespace/módulo: Microsoft.FSharp.Control

Assembly: FSharp.Core (em 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)

Parâmetros

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

    O evento para tratar de uma vez.

  • cancelAction
    Tipo: (unidade -> unidade)

    Uma função opcional para executar em vez disso, de cancelamento quando um cancelamento é emitida.

Valor de retorno

Uma computação assíncrona que aguarda o evento seja chamado.

Comentários

A computação responderá ao cancelamento enquanto aguarda o evento. Se o cancelamento ocorrer, e cancelAction for especificado, em seguida, ele é executado, e a computação continua aguardar o evento. Se cancelAction não for especificado, cancelamento faz com que a computação Cancelar imediatamente.

Exemplo

O exemplo de código a seguir demonstra como usar Async.AwaitEvent para configurar uma operação de arquivo que é executado em resposta a um evento que indica que um arquivo é alterado. Nesse caso, aguardando o evento impede que a tentativa de acessar o arquivo enquanto ele estiver bloqueado.

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)

Saída de exemplo

                

Plataformas

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

Informações sobre versão

O tempo de execução F#

Compatível com: 2.0, 4.0

Silverlight

Compatível com: 3

Consulte também

Referência

Classe Control.Async (F#)

Microsoft.FSharp.Control Namespace (F#)

Histórico de alterações

Date

History

Motivo

Julho de 2010

Exemplo de código adicionado.

Aprimoramento de informações.