我正在尝试创建一个异步工作流,其中有一个主异步循环,在每个循环中执行异步子块。 并且我希望这个异步子块可以被取消,但当它被取消时,我不希望主循环被取消。 我希望它在
我只看到
有没有办法做到这一点?
do! subBlock
之后继续运行。我只看到
Async
中有一个可接受签名的方法(使用CancellationToken
,返回可转换为async
的内容),即Async.StartAsTask
,但似乎它在取消时会挂起; 在下面的代码中,它打印“已取消”,然后什么也没有。open System
open System.Threading
open System.Threading.Tasks
// runs until cancelled
let subBlock =
async {
try
while true do
printfn "doing it"
do! Async.Sleep 1000
printfn "did it"
finally
printfn "cancelled!"
}
[<EntryPoint>]
let main argv =
let ctsRef = ref <| new CancellationTokenSource()
let mainBlock =
//calls subBlock in a loop
async {
while true do
ctsRef := new CancellationTokenSource()
do! Async.StartAsTask(subBlock, TaskCreationOptions.None, (!ctsRef).Token)
|> Async.AwaitTask
printfn "restarting"
}
Async.Start mainBlock
//loop to cancel CTS at each keypress
while true do
Console.ReadLine() |> ignore
(!ctsRef).Cancel()
0
有没有办法做到这一点?