Forcing threads in a service to wait for another thread to finish

I'm writing a service that has five different methods that can take between 5 seconds and 5 minutes to run.

The service will schedule these different methods to run at different intervals.

I don't want any of the methods to run concurrently, so how do I have the methods check to see if another method is running and queue itself to run when it finishes?



If you want simple, and all the methods are in the same class, ou can just use [MethodImpl]:

public void Foo() {...}

public void Bar() {...}

For instance methods, this locks on this; for static methods, this locks on typeof(TheClass).

As such, these lock objects are public - so there is a remote (but genuine) chance that another bit of code might be locking on them. It is generally considered better practice to create your own lock object:

private readonly object syncLock = new object(); // or static if needed

public void Foo() {
   lock(syncLock) {


Aside: a curious fact; the ECMA spec doesn't define a specific pattern for [MethodImpl], even including an example of a private lock, as "valid". The MS spec, however, insists on this/typeof.

Need Your Help

Correct approach of setting up fluent nhibernate syscache with one table and four queries?

nhibernate fluent-nhibernate

My scenario is pretty simple, I have 1 table with about 20 products that I would like to add to level 2 cache (SysCache) using Fluent NHibernate. I query this table 4 different ways so I figure I'd...