[英]Async.Start vs Async.StartChild
假設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...)
}
關鍵區別在於,當您使用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)
它們將在取消主要工作流程時全部取消。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.