views:

1444

answers:

4

I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering [MethodImpl(MethodImplOptions.Synchronized)] and a few ways of using lock(), but I have a few questions/concerns.

It seems like MethodImplOptions.Synchronized will essentially do lock(this). If that's the case, it seems like a thread entering any synchronized method would block all other threads from entering any synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)

Concerning lock(), I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?

Thanks in advance!

A: 

You can expose some static reference or a singleton, and lock() that.

Maybe you can care to explain why you need such locking and what you will use it for?

cruizer
There are a number of application variables and collections/lists which are read and modified by requests. Each request only "cares" about a certain subset of those variables. I'm trying to maximize throughput, so the more granular I can make the locks, the better.
Matthew Cole
OK, but then applying locks/synchronization on the method level does not appear granular to me at all, that's why I asked...
cruizer
The methods themselves only contain the sets that I need to lock - nothing more.
Matthew Cole
A: 

Creating discrete object instances at static/application level is the best way for plain exclusive locking.

Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.

stephbu
+2  A: 

My preference is to create an object specifically for the lock.

private object lockForSomeResource = new object();

in the class that is managing the contentious resource. Jeff Richter posted an article I read some time ago that recommended this.

You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.

Hamish Smith
+1  A: 

Hi,

I have posted a similar question on this forum, that may help you. Following is the link

http://stackoverflow.com/questions/119548/problem-in-writing-to-single-file-in-web-service-in-net

pradeeptp
This looks promising. I'll give it a shot.
Matthew Cole