Reputation: 10332
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();
}
}
}
}
Upvotes: 0
Views: 5176
Reputation: 22733
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.
See this Article (Summary Contains Sample Code), for fruther details.
Upvotes: 1
Reputation: 11647
You should synchronize access to all shared resources (i.e. 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.
Upvotes: 5