gpt4 book ai didi

F#异步;在同一个线程中运行异步表达式,并且能够等待异步操作(例如做!)

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

使用 F# async 进行的一些试验告诉我可以在当前运行的线程 上启动立即。这似乎允许我运行一个异步表达式,它仍然可以传递控制,无论何时进入它内部进行一些异步操作(例如做!),到异步表达式之外的代码。请看下面的简单示例:

open System.Threading

let workThenWait() = async {
printfn "async start"
do! Async.Sleep(1000)
printfn "async end"
}

let demo() =
workThenWait() |> Async.StartImmediate
printfn "main started"
// here I want to wait to the async expression in case it has passed control
printfn "main end"

demo()

我们得到的结果是:

async start
main started
main end
async end

另一方面,如果我使用 StartAsTask(在演示中)执行相同的异步表达式(在本例中为 workThenWait),我可能会在结尾。

我的问题是:

使用前面使用 StartImmediate 的示例,我可以在同一个线程上运行,但也可以在末尾等待异步表达式,以防某些异步操作(例如 do!)被调用并向前传递控制权吗?

最佳答案

我认为您需要 Async.RunSynchronously ( http://msdn.microsoft.com/en-us/library/ee370262.aspx )

更新:好的,现在我更好地理解了你想要什么,并且我能够使用 Async.StartWithContinuations 方法实现这一点。

代码如下:

open System.Threading
let f() =
printfn "main thread: %A" Thread.CurrentThread.ManagedThreadId
let c1 =
async {
printfn "c1 async thread: %A" Thread.CurrentThread.ManagedThreadId
do! Async.Sleep(1000)
return "some result"
}

let continuation s =
printfn "continuation thread: %A" Thread.CurrentThread.ManagedThreadId
printfn "now the code You want after waiting and the result %s" s

Async.StartWithContinuations(
c1,
continuation,
(fun _ -> ()),
(fun _ -> ())
)

printfn "Code that runs during async computation"

现在这绝对不是很可读,因为代码流不是很明显。我找不到更好的解决方案。

关于F#异步;在同一个线程中运行异步表达式,并且能够等待异步操作(例如做!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24578183/

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