我真的锁了这个东西吗
环境: 3 个 Web 服务 2 个位于同一池中 1 个位于不同的应用程序池中。
它们都有相同的代码,试图访问非线程安全的东西,比如它们写入的文件。
我尝试以相同的方式为每个网络服务锁定此代码。我不确定 lock 关键字是否达到了我想要的效果。
我在每个 Web 服务中尝试的一个锁是这样的:
string stringValue
lock (stringValue)
我尝试的另一个锁是:
lock (typeof(MyWebServiceClass))
这些锁会阻止在使用文件时同时写入文件吗?在这种情况下,有多个客户端访问每个 Web 服务。
The environment:
3 web services 2 in the same pool 1 in a different application pool.
They all have the same code trying to access something that is not thread safe say a file that they write to.
I try and lock this code the same way for each web service. I'm not sure if the lock keyword is doing what I want.
One lock I try is this in each web service:
string stringValue
lock (stringValue)
The other lock I try is:
lock (typeof(MyWebServiceClass))
Will these locks prevent any simultaneous writes to the file while it is in use? In this case there are multiple clients hitting each of these web services.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个名为
Mutex
跨应用程序池/进程锁定:C#
lock
关键字是Monitor.Enter()
、Monitor 的语法糖。 Exit()方法在
try/finally
块中调用。Monitor
是一个轻量级(完全托管)同步原语,用于进程内锁定。另一方面,互斥体可以是本地的,也可以是全局的(同一台机器上的进程之间)——全局互斥体,也称为命名互斥体,在整个操作系统中都是可见的,并可用于同步多个应用程序域或进程中的线程。另请参阅 MSDN。
You need a named
Mutex
to lock on across application pools /processes:The C#
lock
keyword is syntactic sugar forMonitor.Enter()
,Monitor.Exit()
method calls in atry/finally
block.Monitor
is a light weight (fully managed) synchronization primitive for in-process locking.A
Mutex
on the other hand can be either local or global (across processes on the same machine) - global mutexes, also called named mutexes, are visible throughout the operating system, and can be used to synchronize threads in multiple application domains or processes. Also see MSDN.我认为您需要使用 互斥体 在 AppDomain 之间锁定。
另外,无论其价值如何,请避免锁定类型。如果其他地方的代码在获得第一个锁后尝试锁定,通常会导致死锁。最好锁定一个唯一目的是充当锁的对象。
例如:
I think you need to use a Mutex to lock between AppDomains.
Also, for what its worth, avoid locking on a type. That can often result in deadlocks if code elsewhere tries to lock after the first lock has been obtained. It's best to lock on an object whose only purpose is to act as a lock.
For example: