[英]WCF service with ConcurrencyMode.Multiple and InstanceContextMode.Single behavior and multithreading safety
I have a service configured with following attributes 我有一个配置了以下属性的服务
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class UserService : IUserServiceContract
{}
Should I use in this scenario locking mechanism for methods implemented in the service? 在这种情况下,是否应该对服务中实现的方法使用锁定机制?
If yes, is this the proper implementation ? 如果是,这是正确的实现吗?
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class UserService : IUserServiceContract
{
private readonly object LockObject = new object();
public Object1 GetObject1()
{
lock (LockObject)
{
using (var ob = new Object1)
{
return ob.Get();
}
}
}
public Object2 GetObject2()
{
lock (LockObject)
{
using (var ob = new Object2)
{
return ob.Get();
}
}
}
}
You should synchronize access to all shared resources (ie to all service fields or properties). 您应该同步对所有共享资源(即对所有服务字段或属性)的访问。
But in this case: 但是在这种情况下:
public Object2 GetObject2()
{
lock (LockObject)
{
using (var ob = new Object2)
{
return ob.Get();
}
}
}
No, there is no need to lock, because there is no shared resource. 不,不需要锁定,因为没有共享资源。 For each call (or message) there is separate call stack, so in this case for separate call would be created separate instance of Object2.
对于每个调用(或消息),都有单独的调用堆栈,因此在这种情况下,将为Object2创建单独的调用。
Yes, I think you're on the right track here and your implementation looks correct. 是的,我认为您的做法正确无误,并且您的实现看起来正确。 When using ConcurrencyMode.Multiple, you will have to make your code thread safe as multiple threads will be hitting the service.
使用ConcurrencyMode.Multiple时,必须确保代码线程安全,因为多个线程将访问该服务。
See this Article (Summary Contains Sample Code) , for fruther details. 有关更多详细信息,请参见本文(摘要中包含示例代码) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.