该场景是RPC over消息队列 - 由于底层机制是异步的,因此客户端应指定在超时之前他们等待响应的时间。作为客户端,您宁愿使用这两个代码片段中的哪一个?用于超时的API设计:TimeoutException或带out参数的布尔返回值?
最重要的是:作为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'
}
OR
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;
}
GetResponseTo()方法的实现会阻塞您的线程 - 使其看起来好像发送请求并同步获得响应 - 即使它发生在异步pub/sub上。 –
另外,如果我露出一个事件像你的建议,这将是由你来决定哪些请求超时(也许你有很多优秀的请求)。 –
@约翰·鲁伊斯:EventArgs的可以为您提供关于timeouted要求,BUF TOR syncronous API的信息,非此非彼TPL不适合提供代码意义 – sll