问题描述
也许这个问题听起来很愚蠢,但是我不了解关于线程和锁定的一些知识,我想得到一个确认().
Maybe the question sounds silly, but I don't understand 'something about threads and locking and I would like to get a confirmation (here's why I ask).
因此,如果我同时有10个服务器和10个请求到每个服务器,则整个服务器场中有100个请求.在不锁定的情况下,多数民众赞成对数据库的请求为100.
So, if I have 10 servers and 10 request in the same time come to each server, that's 100 request across the farm. Without locking, thats 100 request to the database.
如果我做这样的事情:
private static readonly object myLockHolder = new object();
if (Cache[key] == null)
{
lock(myLockHolder)
{
if (Cache[key] == null)
{
Cache[key] = LengthyDatabaseCall();
}
}
}
我将执行多少个数据库请求? 10个? 100?还是我有线程?
How many database requests will I do? 10? 100? Or as much as I have threads?
推荐答案
您具有对象层次结构:
- 您有服务器(10)
- 在每台服务器上您都有进程(可能只有1个-您的服务/应用程序池)
- 在每个进程中都有线程(可能很多)
您的代码将仅将禁止同一服务器上同一进程中的线程访问同时修改Cache
对象.您可以跨进程甚至跨服务器创建锁,但是随着您向上移动层次结构,成本会增加很多.
Your code will only prohibit threads within the same process on the same server access to modify the Cache
object simultaneously. You can create locks across processes and even across servers, but the cost increases a lot as you move up the hierarchy.
使用lock
语句实际上不会锁定任何线程.但是,如果一个线程正在锁中执行代码(即在lock
语句之后的代码块中),则任何其他要获取该锁并执行相同代码的线程都必须等待,直到第一个持有该锁的线程离开代码块并释放锁.
Using the lock
statement does not actually lock any threads. However, if one thread is executing code inside the lock (that is in the block of code following the lock
statement) any other thread that wants to take the lock and execute the same code has to wait until the first thread holding the lock leaves the block of code and releases the lock.
C#lock
语句使用Windows 关键部分,其中采用了轻巧的锁定机制.如果要跨进程锁定,则可以使用 mutex 代替.要跨服务器锁定,可以使用数据库或共享文件.
The C# lock
statement uses a Windows critical section which a lightweight locking mechanism. If you want to lock across processes you can use a mutex instead. To lock across servers you can use a database or a shared file.
正如dkackman指出的那样,.NET具有AppDomain的概念,该概念是一种轻量级进程.每个进程可以有多个AppDomain. C#lock
语句仅锁定单个AppDomain中的资源,并且层次结构的正确描述将在进程下方和线程上方包括AppDomain.但是,在一个过程中,通常只有一个AppDomain会使区分变得无关紧要.
As dkackman has pointed out .NET has the concept of an AppDomain that is a kind of lightweight process. You can have multiple AppDomains per process. The C# lock
statement only locks a resource within a single AppDomain, and a proper description of the hierarchy would include the AppDomain below the process and above the threads. However, quite often you only have a single AppDomain in a process making the distinction somewhat irrelevant.
这篇关于lock()语句会阻塞进程/appdomain中的所有线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!