【问题标题】:How to timeout, or limit the waiting time for a response from an external API如何超时或限制外部 API 响应的等待时间
【发布时间】:2021-01-25 05:22:55
【问题描述】:

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

我的应用程序与 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 解决方案,而不是特定于框架的解决方案。

【问题讨论】:

    标签: asp.net-core client .net-standard apiclient


    【解决方案1】:

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

    Set timeout to an operation

    我选择的解决方案是:

    使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2022-07-01
      相关资源
      最近更新 更多