Async.Start与Async.StartChild

Gus*_*rra 11 f# asynchronous

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

async {
    //(...async stuff...)
    for msg in msgs do 
        asyncSendMsg msg |> Async.Start
    //(...more async stuff...)
}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*cek 21

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

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

// 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()
Run Code Online (Sandbox Code Playgroud)

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