创建了WCF服务端 ServiceHost
怎样不用配置文件 直接用源码就能更改ServiceHost的MaxConcurrentCalls,MaxConcurrentInstances,MaxConcurrentSessions三个属性?
怎样不用配置文件 直接用源码就能更改ServiceHost的MaxConcurrentCalls,MaxConcurrentInstances,MaxConcurrentSessions三个属性?
using System;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;ServiceThrottlingAttribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class ServiceThrottlingAttribute : Attribute, IServiceBehavior
{
public int MaxConcurrentCalls { get; set; }
public int MaxConcurrentInstances { get; set; }
public int MaxConcurrentSessions { get; set; }
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
} public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
var currentThrottle = serviceDescription.Behaviors.Find<ServiceThrottlingBehavior>();
if (currentThrottle == null)
{
serviceDescription.Behaviors.Add(GetConfiguredServiceThrottlingBehaviour());
}
} private ServiceThrottlingBehavior GetConfiguredServiceThrottlingBehaviour()
{
var behaviour = new ServiceThrottlingBehavior();
if (MaxConcurrentCalls > 0)
{
behaviour.MaxConcurrentCalls = MaxConcurrentCalls;
}
if (MaxConcurrentInstances > 0)
{
behaviour.MaxConcurrentInstances = MaxConcurrentInstances;
}
if (MaxConcurrentSessions > 0)
{
behaviour.MaxConcurrentSessions = MaxConcurrentSessions;
}
return behaviour;
}
}使用:
[ServiceThrottlingAttribute(MaxConcurrentCalls=1, MaxConcurrentInstances=1, MaxConcurrentSessions=1)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
...
ServiceThrottlingBehavior throttle;
throttle = new ServiceThrottlingBehavior();
throttle.MaxConcurrentCalls = 1000;
throttle.MaxConcurrentInstances = 1000;
throttle.MaxConcurrentSessions = 1000;
host.Description.Behaviors.Add(throttle);