17

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

and

async {
    //(...async stuff...)
    for msg in msgs do 
        let! child = asyncSendMsg msg |> Async.StartChild
        ()
    //(...more async stuff...)
}
Gustavo Guerra
  • 5,319
  • 24
  • 42

1 Answers1

27

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()

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.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Is there any difference with respect to whether the workflow will start on a new thread vs. a threadpool thread? – ildjarn Mar 08 '13 at 00:06
  • Ok, cool, that's what I guessed but wanted to make sure it was the only difference. Thanks – Gustavo Guerra Mar 08 '13 at 00:07
  • @ildjarn I have not tested or checked this, but I think the starting mechanism is the same - AFAIK, it will be queued in the thread pool in both cases (`StartImmediate` starts work on the _current_ thread). – Tomas Petricek Mar 08 '13 at 00:08
  • 1
    @ildjarn Yes - they are the same. They both use an internal `queueAsync` primitive under the cover (see https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/control.fs#L1852 and https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/control.fs#L1199) – Tomas Petricek Mar 08 '13 at 00:13