简体   繁体   中英

C# / ASP.NET - Web Application locking

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!

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.

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

Issue writing to single file in Web service in .NET

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?

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 eg for reading and updating lists, hashes etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM