如何超时或限制外部API响应的等待时间

问题描述

我一般都遇到过这个问题,但从未真正解决过,但是今天早上我有一个具体案例。

我的应用程序与Despatch Bay Shipping API集成在一起: https://github.com/despatchbay/despatchbay-api-v15/wiki

我不会打扰您所有代码,但是今天早上他们的端点失败了,并且我在这代码中遇到了错误,该行根据我发送的包裹数据要求其API运送服务:

Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company,Box.ToParcel(ParcelValue:=ParcelTotal),DBRecipient)

他们的代码在自己的网站上也失败了。

我通过将上面需要Services对象的代码包装在Try/Catch中来暂时“克服”了这个问题,但是要花很长时间才能真正失败。

那我该怎么写呢?

Try
     Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company,DBRecipient)
Catch
    ' Do stuff it broke
End Try

写类似

Wait for Despatch Bay:    
    Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company,DBRecipient)
But if it takes too long
    'Do stuff,it broke
End waiting for Despatch Bay

我只想超时该API请求的响应,我的整个代码块。

如果有问题,我正在寻找一种.NetStandard解决方案,而不是特定于框架的解决方案。

解决方法

我在这里发现了类似的问题:

Set timeout to an operation

我选择的解决方案是:

使用System.Threading.Tasks;

return salesAssociate.contactInfo.email

转换为VB并期望我的函数返回一个对象,我的实际代码是:

var task = Task.Run(() => obj.PerformInitTransaction());
if (task.Wait(TimeSpan.FromSeconds(30)))
    return task.Result;
else
    throw new Exception("Timed out");