通用主机中的同步发送/回复

1 nservicebus

我试图使用通用主机Windows服务的处理函数同步发送/回复,如下所示.但我认为NServiceBus只在完成句柄功能后才会发送消息(在当前事务完成期间).所以下面的代码将挂起'synchronousHandle.AsyncWaitHandle.WaitOne()'.

这里最好的方法是什么?你能指导我吗?

    Handler constructer

    ConstructorFunction(bus)
    {
                    Bus = bus
    }

    code in the handle function. 
    // sent the message to the bus and wait for the reply

    IMessage response = null;

    var synchronousHandle = Bus.Send(service2queue, requestMessage)
                                            .Register(
                                            (AsyncCallback)delegate(IAsyncResult asyncResult)
                                            {
                                                // Callback block for reply message
                                                // Reply message received
                                                NServiceBus.CompletionResult completionResult = asyncResult.AsyncState as NServiceBus.CompletionResult;
                                                if (completionResult != null && completionResult.Messages.Length > 0)
                                                {
                                                    // Always expecting one IMessage as reply
                                                    response = completionResult.Messages[0];
                                                }
                                            },
                                            null);


// block the current thread till the reply received.
synchronousHandle.AsyncWaitHandle.WaitOne();
Run Code Online (Sandbox Code Playgroud)

谢谢,Ajai

Ste*_*kel 5


nservicebus试图在不应该做的时候尽可能地努力.

来自nservicebus文档:

Bus.Send(request).Register(asyncCallback, state)

Callback only fires on first response, then is cleaned up to prevent memory leaks. 
Doesn’t survive restarts – not suitable for server-side
Run Code Online (Sandbox Code Playgroud)

假设你在服务器端(我猜这里因为你向我们展示了一个消息处理程序)我会考虑重新设计.

service1 gets a notification about messageA
service1 sends message requestMessage to service2
service2 replies with message responseMessage to service1
service1 handles responseMessage and continues processing
Run Code Online (Sandbox Code Playgroud)

如果你想在继续处理之前等待service1中的多个消息,请尝试考虑实现sagas.