Async.Start 与 Async.StartChild [英] Async.Start vs Async.StartChild

查看:22
本文介绍了Async.Start 与 Async.StartChild的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Assuming asyncSendMsg doesn't return anything and I want to start it inside another async block, but not wait for it to finish, is there any difference between this:

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...)
}

推荐答案

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

The key difference is that when you start a workflow with Async.StartChild, it will share the cancellation token with the parent. If you cancel the parent, all children will be cancelled too. If you start the child using Async.Start, then it is a completely independent workflow.

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

Here is a minimal example that demonstrates the difference:

// 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),当主工作流取消时,它们都会被取消.

In this example, if you start the computation using (1), then all work items will finish and print after 2 seconds. If you use (2) they will all be cancelled when the main workflow is cancelled.

这篇关于Async.Start 与 Async.StartChild的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆