更新:2010 年 7 月
產生具有範圍、合作式的取消處理常式,以用於非同步工作流程內。
命名空間/模組路徑: Microsoft.FSharp.Control
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
static member OnCancel : (unit -> unit) -> Async<IDisposable>
// Usage:
Async.OnCancel (interruption)
參數
傳回值
會在未受處置就遭取消時觸發 interruption 的非同步計算。
備註
下列程式碼會產生非同步的計算,就例如位置,取消通知如果發生非同步計算範圍內的 執行期間的任何時間 holder,然後動作 interruption執行執行緒正在執行的取消通知。 這可用來排列,非同步通知的計算的取消通知已發生,就例如藉由設定一的旗標或 deregistering 暫止的 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
輸出
平台
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
請參閱
參考
Microsoft.FSharp.Control 命名空間 (F#)
變更記錄
日期 |
History |
原因 |
|---|---|---|
|
2010 年 7 月 |
加入程式碼範例。 |
資訊加強。 |