Table of contents
Collapse the table of content
Expand the table of content

Async.OnCancel Method (F#)

Den Delimarsky|Last Updated: 8/18/2017
1 Contributor

Generates a scoped, cooperative cancellation handler for use within an asynchronous workflow.

Namespace/Module Path: Microsoft.FSharp.Control

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


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

// Usage:
Async.OnCancel (interruption)


interruption Type: unit->unit

The function that is executed on the thread performing the cancellation.

Return Value

An asynchronous computation that triggers the interruption if it is cancelled before being disposed.


For example, the following code generates an asynchronous computation where, if a cancellation happens any time during the execution of the asynchronous computation in the scope of holder, then action interruption is executed on the thread that is performing the cancellation. This can be used to arrange for a computation to be asynchronously notified that a cancellation has occurred, for example, by setting a flag, or deregistering a pending I/O action.

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


The following code example demonstrates the use of 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."
printfn "Sending cancellation signal."

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


Started computations.
Sending cancellation signal.
Canceling operation.
Canceling operation.


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

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Control.Async Class (F#)

Microsoft.FSharp.Control Namespace (F#)

© 2020 Microsoft