views:

327

answers:

2

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();
    }
  }
 }
}
+2  A: 

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.

Sergey Teplyakov
+1  A: 

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.

Tanner
But in this case there are no shared resources...
Sergey Teplyakov
yes I agree, my assumption was that this was dummy code looking at the various object names in place.
Tanner