有人可以解释一下这个问题吗?虽然我在 ServiceThrotdlingBehavior 中将 InstanceContextMode 和 ConcurrencyMode 设置为 single,并将最大并发调用实例和 session 设置为 1,但我仍然发现至少有 2 个线程正在处理 wcf 请求?
客户端输出:
Client name :kk Instance:1 Thread:13 Time:2013/12/30 12:17:56
Client name :kk Instance:1 Thread:12 Time:2013/12/30 12:17:57
Client name :kk Instance:1 Thread:13 Time:2013/12/30 12:17:58
服务器代码:
Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");
//Create ServiceHost
ServiceHost host
= new ServiceHost(typeof(ClassLibrary1.HelloWorldService), httpUrl);
//Add a service endpoint
host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService)
, new WSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
ServiceThrottlingBehavior stb = new ServiceThrottlingBehavior
{
MaxConcurrentCalls = 1,
MaxConcurrentInstances = 1 ,
MaxConcurrentSessions = 1
};
host.Description.Behaviors.Add(smb);
host.Description.Behaviors.Add(stb);
//Start the Service
host.Open();
客户端代码:
ServiceReference1.HelloWorldServiceClient obj = new ServiceReference1.HelloWorldServiceClient();
for(int i=0;i<15;i++)
{
obj.Call(str);
Thread.Sleep(1000);
}
服务代码:
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract(IsOneWay=true)]
void Call(string ClientName);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
public static int i;
public HelloWorldService()
{
i++;
}
public void Call(string ClientName)
{
Console.WriteLine("Client name :" + ClientName + " Instance:" + i.ToString() + " Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + " Time:" + DateTime.Now.ToString() + "\n\n");
}
}
最佳答案
我不是线程方面的专家,但我会尝试一下并扩展我的评论。
根据 MSDN,ConcurrencyMode.Single表示服务实例是单线程的,不接受可重入调用。如果 InstanceContextMode 属性为 Single,并且在实例为调用提供服务时有其他消息到达,则这些消息必须等到服务可用或消息超时。
您正在调用您的服务,每次连续调用之间有 1 秒的延迟。您的输出也显示了这一点 - 每个调用都比前一个调用晚 1 秒。
我相信在这种情况下线程 ID 是一个转移注意力的东西,因为我希望该服务使用线程池中的可用线程。我在文档中没有看到任何保证每次都会使用相同线程的内容,在我看来,这是一个不合理的期望。
如果您希望从可用线程中获得专用线程,我认为您无法做到这一点。如果您希望该服务一次仅处理一个请求,那么您的方式应该可以做到这一点。
关于单线程 Wcf 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833309/