Issue with lock(this) { ... }

  • Thread starter Thread starter Max Adams
  • Start date Start date
M

Max Adams

All,

I have a multithreaded app (using threadpool). I was under the illusion
that where I used lock( this ) around a segment of code that only one thread
would be allowed access to that segment of code at a time.

The scenario I have is that a part of code creates a document "new.txt" (for
simplicity) and zips it up, I only ever want one "new.txt" so I put this
code inside a lock( this ), however having reviewed my code this does not
act as desired; I see many threads inside this locked section at the same
time :-/

Am I missing something?

MA
 
Max Adams said:
I have a multithreaded app (using threadpool). I was under the illusion
that where I used lock( this ) around a segment of code that only one thread
would be allowed access to that segment of code at a time.

For that one instance, yes.
The scenario I have is that a part of code creates a document "new.txt" (for
simplicity) and zips it up, I only ever want one "new.txt" so I put this
code inside a lock( this ), however having reviewed my code this does not
act as desired; I see many threads inside this locked section at the same
time :-/

Am I missing something?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

Also, have a look at

http://www.pobox.com/~skeet/csharp/threads/
and in particular
http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml
 
Blocking across the entire instance is often the desired effect, I
think the real concern of lock(this) is code outside of the class can
also lock on the object reference, which can cause problems.
 
And besides, lock(this) *doesn't* block across the entire instance. It simply blocks other callers of lock(this) (or external objects that decide to synchronize of that particular instance).

I could theoretcally use lock(this) to only protect one field in my object.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<[email protected]>

Blocking across the entire instance is often the desired effect, I
think the real concern of lock(this) is code outside of the class can
also lock on the object reference, which can cause problems.
 
Back
Top