gpt4 book ai didi

c# - 将大量可观察量聚合成新的可观察量

转载 作者:太空狗 更新时间:2023-10-29 21:55:46 26 4
gpt4 key购买 nike

比方说,我有 1000 个可观察值。现在我想将所有事件聚合到一个新的可观察对象中,一旦所有其他事件都发送了一个事件,它就会触发 OnNext。使用 Rx 做到这一点的最佳方法是什么?

更新:Rx 论坛上的一些很好的反馈,尤其是 Dave Sexton 的反馈。他展示了如何创建采用多个可观察对象的 Zip 扩展方法:http://social.msdn.microsoft.com/Forums/en-US/rx/thread/daaa84db-b560-4eda-871e-e523098db20c/

最佳答案

F# 中有一个 MailboxProcessor...出于相同的目的,我会在 C# 中使用 SynchronizationContext。给我几分钟,我会写一个例子。

旁白:这是我在 F# 中执行类似操作的代码......这将需要更多的努力,但在 C# 中使用 Rx 仍然可行。

open System.Diagnostics

let numWorkers = 20
let asyncDelay = 100

type MessageForMailbox =
| DataMessage of AsyncReplyChannel<unit>
| GetSummary of AsyncReplyChannel<unit>

let main =
let actor =
MailboxProcessor.Start( fun inbox ->
let rec loop acc =
async {
let! message = inbox.Receive()
match message with
| DataMessage replyChannel -> replyChannel.Reply(); return! loop acc
| GetSummary replyChannel -> replyChannel.Reply(); return! loop acc
}

loop 0 // seed for acc
)

let codeBlocks = [for i in 1..numWorkers ->
async {
do! Async.Sleep asyncDelay
return! actor.PostAndAsyncReply DataMessage
} ]

while true do
printfn "Concurrent started..."
let sw = new Stopwatch()
sw.Start()
codeBlocks |> Async.Parallel |> Async.RunSynchronously |> ignore
actor.PostAndReply GetSummary
sw.Stop()
printfn "Concurrent in %d millisec" sw.ElapsedMilliseconds
printfn "efficiency: %d%%" (int64 (asyncDelay * 100) / sw.ElapsedMilliseconds)

printfn "Synchronous started..."
let sw = new Stopwatch()
sw.Start()
for codeBlock in codeBlocks do codeBlock |> Async.RunSynchronously |> ignore
sw.Stop()
printfn "Synchronous in %d millisec" sw.ElapsedMilliseconds
printfn "efficiency: %d%%" (int64 (asyncDelay * numWorkers * 100) / sw.ElapsedMilliseconds)

main

关于c# - 将大量可观察量聚合成新的可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4349067/

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