我正在通过 WCF 使用 Web 服务,并且我想将服务方法调用限制为每秒 N 次。有没有一个类可以帮助我实现这一目标。或者我是否需要手动更新计数并每秒重置一次。
最佳答案
这是一篇关于 throttle 的有用文章
您可以在代码中使用内置的 throttle 方法:
ServiceHost host = new ServiceHost(
typeof(MyContract),
new Uri("http://localhost:8080/MyContract"));
host.AddServiceEndpoint("IMyContract", new WSHttpBinding(), "");
System.ServiceModel.Description.ServiceThrottlingBehavior throttlingBehavior =
new System.ServiceModel.Description.ServiceThrottlingBehavior();
throttlingBehavior.MaxConcurrentCalls = 16;
throttlingBehavior.MaxConcurrentInstances = Int32.MaxValue;
throttlingBehavior.MaxConcurrentSessions = 10;
host.Description.Behaviors.Add(throttlingBehavior);
host.Open();
或者将它们放入 web.config 中:
<system.serviceModel>
<services>
<service
name="IMyContract"
behaviorConfiguration="myContract">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MyContract"/>
</baseAddresses>
</host>
<endpoint
name="wsHttp"
address=""
binding="wsHttpBinding"
contract="IMyContract">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="myContract">
<serviceMetadata httpGetEnabled="True" />
<serviceThrottling
maxConcurrentCalls="16"
maxConcurrentInstances="2147483647"
maxConcurrentSessions="10"/>
</behavior>
</serviceBehaviors>
</behaviors>
关于c# - throttle - 每秒最大方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8927606/