简体   繁体   English

C#/ ASP.NET-Web应用程序锁定

[英]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. 我正在使用C#/ ASP.NET Web应用程序,在很多情况下需要锁定。 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. 我一直在考虑[MethodImpl(MethodImplOptions.Synchronized)]和使用lock()的几种方法,但是我有一些问题/疑虑。

It seems like MethodImplOptions.Synchronized will essentially do lock(this)`. 看起来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. 到那时,似乎我也可以使用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? 关于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. 杰夫·里希特(Jeff Richter)发布了我前一段时间读过的一篇推荐该文章的文章

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 在.NET中写入Web服务中单个文件的问题

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. 还应该考虑应用程序级别的读取器/写入器锁定实例是否也可以帮助提高应用程序的并发性,例如用于读取和更新列表,哈希等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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