gpt4 book ai didi

asynchronous - f# async 什么时候检查它的 CancellationToken?

转载 作者:行者123 更新时间:2023-12-04 04:09:05 25 4
gpt4 key购买 nike

我在看 F# for fun and profit - Asynchronous programming .下 取消工作流程 他们有以下示例:

let testLoop = async {
for i in [1..100] do
// do something
printf "%i before.." i

// sleep a bit
do! Async.Sleep 10
printfn "..after"
}

open System
open System.Threading

// create a cancellation source
let cancellationSource = new CancellationTokenSource()

// start the task, but this time pass in a cancellation token
Async.Start (testLoop,cancellationSource.Token)

// wait a bit
Thread.Sleep(200)

// cancel after 200ms
cancellationSource.Cancel()
关于这一点,他们说:

In F#, any nested async call will check the cancellation token automatically!

In this case it was the line:

do! Async.Sleep(10) 

As you can see from the output, this line is where the cancellation happened.


但是,对于我(VS2010、F# 2.0、F# Interactive),我得到以下输出。注意它如何打印 ..after在我取消 token 之后。他们只是错了吗?
1 before....after
2 before....after
3 before....after
4 before....after
5 before....after
6 before....after
7 before....after
8 before....after
9 before....after
10 before....after
11 before....after
12 before....after
13 before..
val cancellationSource : CancellationTokenSource

>
..after
因此,也许在输入 Async.Sleep 时已完成取消检查。 ?不,那么它会打印:
13 before....after
14 before..
val cancellationSource : CancellationTokenSource

>
所以看起来检查实际上是在 for 循环中! IE。它会一直运行,直到被取消后的 for 循环。这是它的工作原理吗?如果我更希望它在 sleep 后检查怎么办?
这个问题似乎暗示取消像我上面描述的那样工作: Can I explicitly check for cancellation / terminate async computation?
编辑:
关于这是否仅在 FSI 2.0 中:如果一个人分别 sleep 200 毫秒、2500 毫秒和 4000 毫秒,以下循环会发生什么?它打印中间吗?
let testLoop = async {
for i in [1..5] do
printf "%i before.." i
do! Async.Sleep 2000
printfn "..middle.."
do! Async.Sleep 1000
printfn "..after"
}

最佳答案

我只在交互式 Fsi 中看到与 F# 2.0 相同的结果。如果我将相同的代码放在一个文件中并运行 fsi cancel.fsx ,那么输出没有最后的 after并且是您期望的。

Fsi v11 和 v12 显示了两种运行代码方式的预期输出。

这表明在以交互方式运行 Fsi v2.0 时存在一些错误或差异,该错误已在更高版本的 FSharp 中修复。

关于asynchronous - f# async 什么时候检查它的 CancellationToken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com