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

    超时值(以毫秒为单位)。 如果未提供该值,则默认值为 -1,它对应于 Infinite

返回值

一个等待输入计算完成的新计算。

备注

此方法通常应在 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#)

修订记录

Date

修订记录

原因

2010 年 7 月

添加了代码示例。

信息补充。