【问题标题】:Async.Start vs Async.StartChildAsync.Start 与 Async.StartChild
【发布时间】:2013-03-07 23:53:18
【问题描述】:

假设asyncSendMsg 没有返回任何内容,我想在另一个异步块中启动它,但不等待它完成,这之间有什么区别:

async {
    //(...async stuff...)
    for msg in msgs do 
        asyncSendMsg msg |> Async.Start
    //(...more async stuff...)
}

async {
    //(...async stuff...)
    for msg in msgs do 
        let! child = asyncSendMsg msg |> Async.StartChild
        ()
    //(...more async stuff...)
}

【问题讨论】:

    标签: asynchronous f#


    【解决方案1】:

    主要区别在于,当您使用Async.StartChild 启动工作流时,它将与父级共享取消令牌。如果取消父级,所有子级也将被取消。如果你用Async.Start启动child,那么它就是一个完全独立的工作流。

    这是一个演示差异的最小示例:

    // Wait 2 seconds and then print 'finished'
    let work i = async {
      do! Async.Sleep(2000)
      printfn "work finished %d" i }
    
    let main = async { 
        for i in 0 .. 5 do
          // (1) Start an independent async workflow:
          work i |> Async.Start
          // (2) Start the workflow as a child computation:
          do! work i |> Async.StartChild |> Async.Ignore 
      }
    
    // Start the computation, wait 1 second and than cancel it
    let cts = new System.Threading.CancellationTokenSource()
    Async.Start(main, cts.Token)
    System.Threading.Thread.Sleep(1000)    
    cts.Cancel()
    

    在本例中,如果您使用(1) 开始计算,则所有工作项将在 2 秒后完成并打印。如果您使用(2),它们将在主工作流取消时全部取消。

    【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2016-03-23
    相关资源
    最近更新 更多