Metodo Async.OnCancel (F#)

Genera un gestore di annullamenti cooperativo e con un ambito definito da utilizzare all'interno di un flusso di lavoro asincrono.

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

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

// Signature:
static member OnCancel : (unit -> unit) -> Async<IDisposable>

// Usage:
Async.OnCancel (interruption)

Parametri

  • interruption
    Tipo: unit -> unit

    Funzione eseguita sul thread che effettua l'annullamento.

Valore restituito

Calcolo asincrono che attiva l'interruzione in caso di annullamento prima dell'eliminazione.

Note

Ad esempio, il seguente codice genera ad esempio un calcolo asincrono in cui, se si verifica un annullamento in qualsiasi momento durante l'esecuzione del calcolo asincrono nell'ambito di holder, l'elemento dell'azione interruption viene eseguito sul thread che esegue l'annullamento.In questo modo è possibile stabilire che a un calcolo venga notificato in modo asincrono che si è verificato un annullamento, ad esempio impostando un flag o annullando la registrazione di un'azione di I/O in attesa.

async { use! holder = Async.OnCancel interruption ... }

Esempio

Nell'esempio di codice seguente viene illustrato l'utilizzo di Async.OnCancel.

// This is a simulated cancellable computation. It checks the token source
// to see whether the cancel signal was received.
let computation (tokenSource:System.Threading.CancellationTokenSource) =
    async {
        use! cancelHandler = Async.OnCancel(fun () -> printfn "Canceling operation.")
        // Async.Sleep checks for cancellation at the end of the sleep interval,
        // so loop over many short sleep intervals instead of sleeping
        // for a long time.
        while true do
            do! Async.Sleep(100)
    }

let tokenSource1 = new System.Threading.CancellationTokenSource()
let tokenSource2 = new System.Threading.CancellationTokenSource()

Async.Start(computation tokenSource1, tokenSource1.Token)
Async.Start(computation tokenSource2, tokenSource2.Token)
printfn "Started computations."
System.Threading.Thread.Sleep(1000)
printfn "Sending cancellation signal."
tokenSource1.Cancel()
tokenSource2.Cancel()

// Wait for user input to prevent application termination.
System.Console.ReadLine() |> ignore

Output

  
  
  
  

Piattaforme

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

Informazioni sulla versione

Versioni della libreria di base F#

Supportato in: 2,0, 4,0, portabile

Vedere anche

Riferimenti

Classe Control.Async (F#)

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