WCF:如何将ServiceThrottling行为添加到WCF服务?

时间:2009-04-27 16:45:54

标签: c# wcf web-services throttling

我有以下代码用于返回我的WCF服务实例ServiceClient

    var readerQuotas = new XmlDictionaryReaderQuotas()
    {
        MaxDepth = 6000000,
        MaxStringContentLength = 6000000,
        MaxArrayLength = 6000000,
        MaxBytesPerRead = 6000000,
        MaxNameTableCharCount = 6000000
    };


    var throttlingBehaviour = new ServiceThrottlingBehavior(){MaxConcurrentCalls=500,MaxConcurrentInstances=500,MaxConcurrentSessions = 500}; 
    binding = new WSHttpBinding(SecurityMode.None) {MaxReceivedMessageSize = 6000000, ReaderQuotas = readerQuotas};

    dualBinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None)
                      {MaxReceivedMessageSize = 6000000, ReaderQuotas = readerQuotas};

    endpointAddress = new EndpointAddress("http://localhost:28666/DBInteractionGateway.svc"); 

    return new MusicRepo_DBAccess_ServiceClient(new InstanceContext(instanceContext), dualBinding, endpointAddress);

最近我遇到了一些超时问题,所以我决定添加限制行为,如下:

    var throttlingBehaviour = new ServiceThrottlingBehavior () {
        MaxConcurrentCalls=500, 
        MaxConcurrentInstances=500,
        MaxConcurrentSessions = 500
    }; 

我的问题是,我应该在上面的代码中将throttlingBehaviour添加到MusicRepo_DBAccess_ServiceClient个实例中吗?


我在网上发现的一些例子中,他们正在做这样的事情:

ServiceHost host = new ServiceHost(typeof(MyService));
ServiceThrottlingBehavior throttleBehavior = new ServiceThrottlingBehavior
{
    MaxConcurrentCalls = 40,
    MaxConcurrentInstances = 20,
    MaxConcurrentSessions = 20,
};
host.Description.Behaviors.Add(throttleBehavior);
host.Open();

请注意,在上面的代码中,他们使用ServiceHost而我不是,然后他们打开它(使用Open()),而我打开MusicRepo_DBAccess_ServiceClient实例...这让我感到困惑。

3 个答案:

答案 0 :(得分:18)

可以在代码中完成,就像我一样,在运行时配置。

vb版本:

    Dim stb As New ServiceThrottlingBehavior
    stb.MaxConcurrentSessions = 100
    stb.MaxConcurrentCalls = 100
    stb.MaxConcurrentInstances = 100
    ServiceHost.Description.Behaviors.Add(stb)

c#version:

    ServiceThrottlingBehavior stb = new ServiceThrottlingBehavior {
        MaxConcurrentSessions = 100,
        MaxConcurrentCalls = 100,
        MaxConcurrentInstances = 100
    };
    ServiceHost.Description.Behaviors.Add(stb);

答案 1 :(得分:6)

限制是服务端(服务器)行为而不是客户端

答案 2 :(得分:3)

您可以使用行为在afaik配置文件中指定行为,并且生成的客户端将遵守。

为简洁起见,排除了一些配置部分

<service 
    behaviorConfiguration="throttleThis" />

        <serviceBehaviors>
            <behavior name="throttleThis">
                <serviceMetadata httpGetEnabled="True" />
                <serviceThrottling
                    maxConcurrentCalls="40"
                    maxConcurrentInstances="20"
                    maxConcurrentSessions="20"/>
            </behavior>
        </serviceBehaviors>