[newbie] Monitor

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I've read that I can only pass references to monitor objects - but how can I
do that? I just wanted a .net equivalent to the C++ CCriticalSection class.
How can I declare a dummy reference to any object (I don't intend to use at
all) to create a section of my code that is only executed by ONE thread at
the same time?

Thanks,

Peter
 
The simplest shortest answer is (assuming c#):

lock(this)
{
//thread safe code
}

Obviously there's a lot more to be said but there's plenty of discussion
around if you google it.
 
Peter Schmitz said:
I've read that I can only pass references to monitor objects - but how can I
do that? I just wanted a .net equivalent to the C++ CCriticalSection class.
How can I declare a dummy reference to any object (I don't intend to use at
all) to create a section of my code that is only executed by ONE thread at
the same time?

Just create a variable of type object, and create a new instance of
object:

object myLock = new object();

I would recommend *against* locking on "this" - see
http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml

Alternatively, you could have specific lock objects which aids
readability - see
http://www.pobox.com/~skeet/csharp/threads/alternative.shtml
 
Back
Top