我想在F#中实现CCR框架端口的概念(因为.Net 4.0不支持CCR )。我知道可以使用F#中的F#类来完成这个任务。这对于简单的接收仲裁者来说是完美的,但我需要交织仲裁器的概念,即我想控制哪些消息被单独处理,哪些消息同时处理。到目前为止,我还不知道在F#中实现这一点,我将感谢您的帮助。
发布于 2011-04-28 16:33:38
我对CCR不是很熟悉,但我会试着回答--我的理解是交错仲裁者的行为有点像ReaderWriterLock。也就是说,您可以指定一些可以并行运行的操作(读)和一些独占的操作(写)。
下面的代理是实现它的一种方法(不是测试,而是类型检查:-)。代理公开两个公共使用的操作。最后一个是内部的:
type Message<'T> =
| PerformReadOperation of ('T -> Async<unit>)
| PerformWriteOperation of ('T -> Async<'T>)
| ReadOperationCompletedPerformReadOperation,给它一个应该使用状态运行(一次)并可能与其他读取操作并行运行的操作。通过发送代理PerformWriteOperation,代理以某种初始状态开始:
let initial = // initial state代理的其余部分使用两个循环实现:
let interleaver = MailboxProcessor.Start(fun mbox ->
// Asynchronously wait until all read operations complete
let rec waitUntilReadsComplete reads =
if reads = 0 then async { return () }
else mbox.Scan(fun msg ->
match msg with
| ReadOperationCompleted -> Some(waitUntilReadsComplete (reads - 1))
| _ -> None)
let rec readingLoop state reads = async {
let! msg = mbox.Receive()
match msg with
| ReadOperationCompleted ->
// Some read operation completed - decrement counter
return! readingLoop state (reads - 1)
| PerformWriteOperation(op) ->
do! waitUntilReadsComplete reads
let! newState = op state
return! readingLoop newState 0
| PerformReadOperation(op) ->
// Start the operation in background & increment counter
async { do! op state
mbox.Post(ReadOperationCompleted) }
|> Async.Start
return! readingLoop state (reads + 1) }
readingLoop initial 0)发布于 2011-04-29 05:11:39
为了添加到Tomas建议的解决方案中,如果您不想向邮箱的使用者公开" ReadOperationCompleted“消息(因为此消息是内部的,并且在当前的实现中可以由邮箱的任何使用者发送),可以在主邮箱处理器函数中创建一个单独的邮箱,它将接受两条消息:ReadOperationCompleted和WaitForReadCompleted (主邮箱将与PostAndAsyncReply一起使用),因为只有在所有读取操作完成后才会对此消息作出响应。此外,“读”表示的“读”计数将被移动到这个新的内部邮箱,因为该状态被这个内部邮箱封装。
https://stackoverflow.com/questions/5821133
复制相似问题