共用方式為


Async.StartChild<'T> 方法 (F#)

啟動非同步工作流程內的子計算。這允許同時執行多個非同步計算。

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

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

// Signature:
static member StartChild : Async<'T> * ?int -> Async<Async<'T>>

// Usage:
Async.StartChild (computation)
Async.StartChild (computation, millisecondsTimeout = millisecondsTimeout)

參數

  • computation
    型別:Async<'T>

    子計算。

  • millisecondsTimeout
    型別:int

    逾時值 (以毫秒為單位)。如果未提供值,則會使用對應至 Infinite 的預設值 -1。

傳回值

等待輸入計算完成的新計算。

備註

這個方法一般應該做為 F# 非同步工作流程中 let! 繫結的緊鄰右邊項目,亦即:

 async { 
    ...
    let! completor1 = childComputation1
    |> Async.StartChild
    let! completor2 = childComputation2
    |> Async.StartChild
    ... 
    let! result1 = completor1
    let! result2 = completor2
     ... }

以這種方式使用時,每次使用 StartChild 都會啟動 childComputation 執行個體,並傳回 completor 物件,表示計算會等待作業完成。執行時,completor 會等待 childComputation 完成。

範例

下列程式碼範例說明如何使用 Async.StartChild

open System.Windows.Forms

let bufferData = Array.zeroCreate<byte> 100000000

let asyncChild filename =
        async {
            printfn "Child job start: %s" filename
            use outputFile = System.IO.File.Create(filename)
            do! outputFile.AsyncWrite(bufferData)
            printfn "Child job end: %s " filename
        }

let asyncParent =
        async {
            printfn "Parent job start."
            let! childAsync1 = Async.StartChild(asyncChild "longoutput1.dat")
            let! childAsync2 = Async.StartChild(asyncChild "longoutput2.dat")
            let! result1 = childAsync1
            let! result2 = childAsync2
            printfn "Parent job end."
        }


let form = new Form(Text = "Test Form")
let button = new Button(Text = "Start")
form.Controls.Add(button)
button.Click.Add(fun args -> Async.Start(asyncParent)
                             printfn "Completed execution." )
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#)