Share via


Async.OnCancel-Methode (F#)

Generiert einen bereichsbezogenen kooperativen Abbruchhandler zur Verwendung in einem asynchronen Workflow.

Namespace/Modulpfad: Microsoft.FSharp.Control

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

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

// Usage:
Async.OnCancel (interruption)

Parameter

  • interruption
    Typ: unit -> unit

    Die Funktion, die in dem Thread ausgeführt wird, der den Abbruch ausführt.

Rückgabewert

Eine asynchrone Berechnung, die die Unterbrechung auslöst, wenn der Abbruch vor der Freigabe erfolgt.

Hinweise

Beispiel: Folgender Code erstellt eine asynchrone Berechnung, und wenn während ihrer Ausführung im Gültigkeitsbereich von holder ein Abbruch erfolgt, wird die Aktion interruption für den Thread ausgeführt, der den Abbruch ausführt. Damit kann eine Berechnung so vorbereitet werden, dass sie asynchron benachrichtigt wird, dass ein Abbruch erfolgt ist, z. B. durch Festlegen eines Flags oder Aufheben der Registrierung einer ausstehenden E/A-Aktion.

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

Beispiel

Im folgenden Codebeispiel wird die Verwendung von Async.OnCancel veranschaulicht.

// 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

          

Plattformen

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

Versionsinformationen

F#-Runtime

Unterstützt in: 2.0, 4.0

Silverlight

Unterstützt in: 3

Siehe auch

Weitere Ressourcen

Control.Async-Klasse (F#)

Microsoft.FSharp.Control-Namespace (F#)

Änderungsprotokoll

Datum

Versionsgeschichte

Grund

Juli 2010

Codebeispiel hinzugefügt.

Informationsergänzung.