HPT
HPT

Reputation: 351

WCF service and lock keyword

assume I have a hosted wcf service in a console application like this:

public class MyService : IContract
{
  public static readonly object _locker_ = new object();

  public static void DoSomething()
  {
    lock (_locker_)
    {
      //block 1
      DoAnotherWork();
    }
  }

  void IContract.Foo1()
  {
    lock (_locker_)
    {
      //block 2
      DoSomeWork();
    }
  }

  void IContract.Foo2()
  {
    DoSomething();
  }
}

does this insures that only one client is in block 1? or block 2?

Upvotes: 1

Views: 2950

Answers (2)

StuartLC
StuartLC

Reputation: 107387

You have only one lock, so only one method can obtain the lock at any point in time. You would need separate locks for DoSomeWork and DoAnotherWork if they are to be run in parallel.

Note also that you would need to consider the InstanceContextMode of your WCF service when considering threading - the default is PerCall.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064114

A static lock object is per-appdomain; so "block 1" and "block 2" only allow a single caller. Ultimately, yes. As long as you only have one appdomain ;p

Note that locks are re-entrant, so the thread with the lock can call the methods again without deadlocking itself (but not via WCF; only via regular C# method calling).

Upvotes: 1

Related Questions