我经常遇到这个问题,但从未真正解决过,但今天早上我有一个具体的案例。
我的应用程序与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, Box.ToParcel(ParcelValue:=ParcelTotal), DBRecipient)
Catch
' Do stuff it broke
End Try
写一些类似的东西
Wait for Despatch Bay:
Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company, Box.ToParcel(ParcelValue:=ParcelTotal), DBRecipient)
But if it takes too long
'Do stuff, it broke
End waiting for Despatch Bay
我只想超时API请求的响应,而不是我的整个代码块。
如果重要的话,我正在寻找.NetStandard
解决方案,而不是特定于框架的解决方案。
我在这里发现了类似的问题:
将超时设置为操作
我选择的解决方案是:
使用System.Threading.Tasks;
var task = Task.Run(() => obj.PerformInitTransaction());
if (task.Wait(TimeSpan.FromSeconds(30)))
return task.Result;
else
throw new Exception("Timed out");
转换为VB并期望我的函数返回一个对象,我的实际代码是:
Dim Services As dbShipping.ServiceType()
Dim ServicesTask As Task(Of dbShipping.ServiceType()) = Task.Run(Function() DespatchBay.Services.Get(Company, Box.ToParcel(ParcelValue:=ParcelTotal), DBRecipient))
If ServicesTask.Wait(TimeSpan.FromSeconds(5)) Then
Services = ServicesTask.Result
Else
Log.Report("It took too long to get dispatch bay records so abandon", TLog.Level.Warning)
End If