将大量可观察量聚合为新的可观察量

时间:2010-12-03 19:18:23

标签: c# .net system.reactive

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

更新: 在Rx论坛上有一些很棒的反馈,特别是Dave Sexton。他展示了如何创建一个带有多个可观察量的Zip扩展方法:http://social.msdn.microsoft.com/Forums/en-US/rx/thread/daaa84db-b560-4eda-871e-e523098db20c/

1 个答案:

答案 0 :(得分:2)

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