共用方式為


Async.StartImmediate 方法 (F#)

直接從目前的作業系統執行緒開始,傳回非同步計算。

**命名空間/模組路徑:**Microsoft.FSharp.Control

組件:FSharp.Core (在 FSharp.Core.dll 中)

// Signature:
static member StartImmediate : Async<unit> * CancellationToken option -> unit

// Usage:
Async.StartImmediate (computation)
Async.StartImmediate (computation, cancellationToken = cancellationToken)

參數

  • computation
    型別:Async<unit>

    要執行的非同步計算。

  • cancellationToken
    型別:CancellationToken

    要與計算產生關聯的取消語彙基元。如果未提供這個參數,則會使用預設值。

備註

如果未提供取消語彙基元,則會使用預設的取消語彙基元。

範例

下列程式碼範例示範如何使用 Async.StartImmediate 啟動目前執行緒上的非同步計算。通常,非同步作業需要更新 UI,此作業一律應在 UI 執行緒上進行。當您的非同步作業需要透過更新使用者介面開始進行時,選擇 Async.StartImmediate 會比在執行緒集區執行緒上啟動非同步作業的 Async.Start 更好。


open System.Windows.Forms

let bufferData = Array.zeroCreate<byte> 100000000

let async1 (button : Button) =
     async {
       button.Text <- "Busy"
       button.Enabled <- false
       let context = System.Threading.SynchronizationContext.Current
       do! Async.SwitchToThreadPool()
       use outputFile = System.IO.File.Create("longoutput.dat")
       do! outputFile.AsyncWrite(bufferData)
       do! Async.SwitchToContext(context)
       button.Text <- "Start"
       button.Enabled <- true
     }


let form = new Form(Text = "Test Form")
let button = new Button(Text = "Start")
form.Controls.Add(button)
button.Click.Add(fun args -> Async.StartImmediate(async1 button))
Application.Run(form)

平台

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

版本資訊

F# 核心程式庫版本

支援版本:2.0, 4.0,可攜式執行檔 (PE)。

請參閱

參考

Control.Async 類別 (F#)

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