【问题标题】:Programmatically set WCF timeout in debug mode在调试模式下以编程方式设置 WCF 超时
【发布时间】:2010-12-22 00:50:07
【问题描述】:

我在服务器和客户端(均用 C# 编写)之间使用 WCF 进行通信。

在发布模式下,超时应设置为 ~20 秒,但在调试模式下,我想将它们设置为更高的值,以便我可以在不发生超时的情况下调试/单步执行代码。

我知道我可以通过修改 app.config 文件来更改超时。但是,我有两个不同的绑定和 4 个超时值,所以我必须在几个地方进行更改,而且很容易忘记。

为了解决这个问题,我想在我的代码中有一个小的#if DEBUG 部分,它以编程方式将超时值更改为 1 小时。

我尝试使用以下代码来执行此操作:

Configuration configuration = 
       ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup serviceModel = 
       ServiceModelSectionGroup.GetSectionGroup(configuration); 

BindingsSection bindings = serviceModel.Bindings;

foreach (var configuredBinding in bindings.WSHttpBinding.ConfiguredBindings)
{
 configuredBinding.CloseTimeout = new TimeSpan(0, 30, 0);
 configuredBinding.OpenTimeout = new TimeSpan(0, 30, 0);

但是 *Timeout 属性是只读的,所以我得到一个编译错误。

我不喜欢以编程方式从头开始创建绑定的想法。如果我更改 app.config 中的某些属性,我必须记住在代码中进行相同的更改,以确保调试行为类似于发布行为(超时除外..)

如何处理?

【问题讨论】:

    标签: wcf configuration timeout


    【解决方案1】:

    您可以执行以下操作:

    • 在代码中创建绑定和端点
    • 设置绑定实例的超时时间
    • 然后使用这两个元素创建您的客户端代理

    类似:

    BasicHttpBinding myBinding = new BasicHttpBinding("ConfigName");
    myBinding.CloseTimeout = .......
    myBinding.OpenTimeout = .......
    myBinding.ReceiveTimeout = .......
    myBinding.SendTimeout = .......
    
    EndpointAddress myEndpoint = new EndpointAddress("http://server:8181/yourservice");
    
    YourServiceClient proxy = new YourServiceClient(myBinding, myEndpoint);
    

    这样,您可以在描述绑定超时时利用基本配置,但您可以调整您想要的设置并从中创建您的客户端代理。

    【讨论】:

      【解决方案2】:

      您可以在 web.config 中创建第二个绑定并设置更长的 sendTimeout。

              if (debug)
              {
                  proxy =  new MyClient("WSHttpBinding_MyLocal");
              }
              else
              {
                  proxy = new MyClient("WSHttpBinding_MyDev");
              }
      
              <wsHttpBinding>
                  <binding name="WSHttpBinding_MyLocal" closeTimeout="00:01:00"
                      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:20:00"
      

      ...

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多