gpt4 book ai didi

c# - 超时的 API 设计 : TimeoutException or boolean return with out parameter?

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:40 25 4
gpt4 key购买 nike

场景是消息队列上的 RPC - 由于底层机制是异步的,客户端应该指定他们希望在超时前等待响应的时间。作为客户,您更愿意使用这两个代码片段中的哪一个?

最重要的是:作为 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;
}

最佳答案

无论是第一个还是第二个,我都想使用 Task Parallel Library ,这是从 .NET 4.5 开始推荐的所有异步处理方式:

Task<IEvent> task = _eventMgr.GetResponseToAsync(myRequest);

if (task.Wait(myTimeSpan))
{
// I got a response!
}
else
{
// I didn't get a response... :(
}

关于c# - 超时的 API 设计 : TimeoutException or boolean return with out parameter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com