共用方式為


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

更新:2010 年 7 月

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

命名空間/模組路徑: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 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#)

變更記錄

日期

History

原因

2010 年 7 月

加入程式碼範例。

資訊加強。