【发布时间】:2011-11-23 22:07:57
【问题描述】:
该场景是基于消息队列的 RPC - 由于底层机制是异步的,客户端应指定在超时之前他们希望等待响应的时间。作为客户端,你更愿意使用这两个代码 sn-ps 中的哪一个?
最重要的是:作为 GetResponseTo() 方法的用户,为什么您更喜欢其中一个?您的选择如何使您的代码更具扩展性、可读性、可测试性等?
try
{
IEvent response = _eventMgr.GetResponseTo(myRequest, myTimeSpan);
// I have my response!
}
catch(TimeoutException te)
{
// I didn't get a response to 'myRequest' within 'myTimeSpan'
}
或
IEvent myResponse = null;
if (_eventMgr.GetResponseTo(myRequest, myTimeSpan, out myResponse)
{
// I got a response!
}
else
{
// I didn't get a response... :(
}
供您参考,下面是 GetResponseTo() 的当前实现:
public IEvent GetResponseTo(IEvent request, TimeSpan timeout)
{
if (null == request) { throw new ArgumentNullException("request"); }
// create an interceptor for the request
IEventInterceptor interceptor = new EventInterceptor(request, timeout);
// tell the dispatcher to watch for a response to this request
_eventDispatcher.AddInterceptor(interceptor);
// send the request
_queueManager.SendRequest(request);
// block this thread while we wait for a response. If the timeout elapses,
// this will throw a TimeoutException
interceptor.WaitForResponse();
// return the intercepted response
return interceptor.Response;
}
【问题讨论】: