1

我们有一个 SLA,第三方 RESTfull Web 服务必须在 5 秒内返回响应。否则我们需要中止服务调用并执行其他部分的业务逻辑。

有人可以帮助我了解如何使用 C#.Net。

4

2 回答 2

1

如果您使用 WCF 调用外部 Web 服务,则只需将客户端端点绑定配置中的 sendTimeout 值配置为 5 秒。然后,如果客户端代理对象没有从外部服务获得回复,则会抛出 TImeoutException,您可以处理并继续。示例绑定配置如下所示:

<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="myExternalBindingConfig"
               openTimeout="00:01:00"
               closeTimeout="00:01:00"
               sendTimeout="00:05:00"
               receiveTimeout="00:01:00">
       </binding>
    </basicHttpBinding>
  </bindings>
</system.serviceModel>
于 2012-09-01T23:41:38.163 回答
0

让我先提供“标准免责声明”作为我的回答的序言,我将在这里提供的部分实践被认为是不好的,因为可能存在处理非托管代码的问题。话虽如此,这里有一个答案:

void InitializeWebServiceCall(){

    Thread webServiceCallThread = new Thread(ExecuteWebService);
    webServiceCallThread.Start();
    Thread.Sleep(5000); // make the current thread wait 5 seconds
    if (webServiceCallThread.IsAlive()){
      webServiceCallThread.Abort(); // warning for deprecated/bad practice call!!
    }
}

static void ExecuteWebService(){

    // the details of this are left to the consumer of the method
    int x = WebServiceProxy.CallWebServiceMethodOfInterest();
    // do something fascinating with the result

}

调用 Thread.Abort() 自 .NET 2.0 起已弃用,并且通常被认为是一种糟糕的编程实践,主要是因为可能与非托管代码进行不利交互。当然,与使用代码相关的风险是由您来评估的。

于 2012-09-01T23:34:59.277 回答