假设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...)
}发布于 2013-03-08 08:02:32
关键区别在于,当您使用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()在此示例中,如果使用(1)开始计算,则所有工作项将在2秒后完成并打印。如果您使用(2),它们将在主工作流取消时全部取消。
https://stackoverflow.com/questions/15284209
复制相似问题