What to use instead of the “lock” statement when the code is running on multiple machines?

冷暖自知 提交于 2019-12-03 11:20:42
Kit

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

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.

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.

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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!