Async.OnCancel 方法 (F#)

更新:2010 年 7 月

生成一个限定范围的协作取消处理程序,以便在异步工作流内使用。

命名空间/模块路径: Microsoft.FSharp.Control

程序集:FSharp.Core(在 FSharp.Core.dll 中)

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

// Usage:
Async.OnCancel (interruption)

参数

  • interruption
    类型:unit -> unit

    在执行取消操作的线程上执行的函数。

返回值

一个异步计算,如果它在释放前取消,则会触发中断。

备注

例如,以下代码生成一个异步计算,在 holder 范围内执行该异步计算的过程中,只要发生取消操作,都会在执行取消操作的线程上执行操作 interruption。 利用这一点,可进行一些安排,以便通过设置标志或取消注册挂起的 I/O 操作等方式,异步通知计算已发生取消。

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

示例

下面的代码示例演示了 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

          

平台

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

版本信息

F# 运行时

受以下版本支持:2.0、4.0

Silverlight

受以下版本支持:3

请参见

参考

Control.Async 类 (F#)

Microsoft.FSharp.Control 命名空间 (F#)

修订记录

Date

修订记录

原因

2010 年 7 月

添加了代码示例。

信息补充。