Async.OnCancel 方法 (F#)
產生具有範圍、合作式的取消處理常式,以用於非同步工作流程內。
**命名空間/模組路徑:**Microsoft.FSharp.Control
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
static member OnCancel : (unit -> unit) -> Async<IDisposable>
// Usage:
Async.OnCancel (interruption)
參數
傳回值
會在未受處置就遭取消時觸發 interruption 的非同步計算。
備註
例如,下列程式碼會產生非同步計算,在這個計算中,如果在 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 8 中, Windows 7, Windows Server 2012 上, Windows Server 2008 R2
版本資訊
F# 核心程式庫版本
支援版本:2.0, 4.0,可攜式執行檔 (PE)。