问题
The lock statement ensures that one thread does not enter a critical section of code while another thread is in the critical section. However, it won't work if the workload is spread across a farm of servers (e.g. a few IIS servers + a load balancer).
Does .NET support such a scenario?
Is there any class that can be used to control the execution of a critical code section by threads running on multiple machines?
If not, is there any standard method of handling such problems?
This question was inspired by a discussion that started here but is not limited to SharePoint or ASP.NET.
回答1:
If you have access to a centralized SQL Server instance, you can use it to act as a distributed lock coordinator and manage the application locks using the sp_getapplock and sp_releaseapplock stored procedures.
Application Locks (or Mutexes) in SQL Server 2005
回答2:
The lock
statement is only useful for sharing resources within a process.
The Mutex
and EventWaitHandle
classes are useful for sharing resources among multiple processes on a single machine when using names that start with "Global\"
.
Beyond that, you will have to implement something outside .NET, like using sp_getapplock
/sp_releaseapplock
on a shared SQL database.
回答3:
Since a network of machines in a standard scenario does not operate on shared memory, they have no global view of a single variable that can be used for synchronization. Therefore, you have to implement locks by means of message passing.
If you want to lock shared resources, you can have a central "master" regulate access to that resource.
Edit: If what you need is not sharing resources (e.g. a barrier), you can use for example MSMQ to pass messages between the machines. Probably sockets are too low level.
回答4:
There is no way to implement an inter-machine threading control with ASP.NET right now. But this can be implemented via a higher level application architecture. Basically, you would have to implement it yourself using your own business logic.
Architecturally, you should introduce a ILockable interface in your solution, and have classes that need to cease operation at some condition to implement it. Then use a set of Gateways to mutually manage those locks.
回答5:
There is nothing in .Net that can natively support cross-machine locking.
The standard method is to move the responsibility for such things to a single place, possibly a web service (not load balanced!), so it can still be called from multiple locations. Or alternatively, defining a single resource, that's accessible by all (eg database) and using this as the single resource to acquire (eg write key in locks table, if key exists lock cannot be acquired until row removed)
来源:https://stackoverflow.com/questions/8189439/what-to-use-instead-of-the-lock-statement-when-the-code-is-running-on-multiple