[newbie] Monitor

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
 
S

Stelrad Doulton

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.
 
J

Jon Skeet [C# MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top