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

出力

          

プラットフォーム

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#)

履歴の変更

日付

履歴

理由

2010 年 7 月

コード例を追加。

情報の拡充