Web services Web服务调用如何等待N秒并中止

Web services Web服务调用如何等待N秒并中止,web-services,c#-3.0,Web Services,C# 3.0,我们有一个SLA,第三方RESTfull web服务必须在5秒内返回响应。否则,我们需要中止服务调用并执行业务逻辑的其他部分 有人能帮我了解一下如何使用C#.Net。让我在回答之前先提供一个“标准免责声明”,我将在这里提供的部分实践被认为是不好的,因为可能存在处理非托管代码的问题。尽管如此,以下是一个答案: void InitializeWebServiceCall(){ Thread webServiceCallThread = new Thread(ExecuteWebServic

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


有人能帮我了解一下如何使用C#.Net。让我在回答之前先提供一个“标准免责声明”,我将在这里提供的部分实践被认为是不好的,因为可能存在处理非托管代码的问题。尽管如此,以下是一个答案:

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

}

从.NET 2.0开始,调用Thread.Abort()就被弃用,并且通常被认为是一种不好的编程实践,主要是因为可能会与非托管代码发生不利的交互。当然,与使用代码相关的风险由您来评估。

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

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

}

从.NET 2.0开始,调用Thread.Abort()就被弃用,并且通常被认为是一种不好的编程实践,主要是因为可能会与非托管代码发生不利的交互。当然,与使用代码相关的风险由您来评估。

如果您使用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>

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


您使用什么进行web服务调用,WebClient?您使用什么进行web服务调用,WebClient?