Asp.net core 如何超时或限制外部API响应的等待时间
我经常遇到这个问题,从来没有真正解决过,但今天早上我有一个具体的案例 我的应用程序与Dispatch Bay Shipping API集成: 我不会用所有的代码来打扰您,但今天早上他们的端点出现故障,我的代码这一行出现错误,根据我发送的包裹数据从他们的API请求运输服务:Asp.net core 如何超时或限制外部API响应的等待时间,asp.net-core,client,.net-standard,apiclient,Asp.net Core,Client,.net Standard,Apiclient,我经常遇到这个问题,从来没有真正解决过,但今天早上我有一个具体的案例 我的应用程序与Dispatch Bay Shipping API集成: 我不会用所有的代码来打扰您,但今天早上他们的端点出现故障,我的代码这一行出现错误,根据我发送的包裹数据从他们的API请求运输服务: Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company, Box.ToParcel(ParcelValue:=ParcelTot
Dim Services As dbShipping.ServiceType() = DespatchBay.Services.Get(Company, Box.ToParcel(ParcelValue:=ParcelTotal), DBRecipient)
他们的代码在自己的网站上也失败了
通过将需要上述服务
对象的代码包装在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