Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 667
Marek Grzenkowicz Avatar asked Nov 18 '11 21:11

Marek Grzenkowicz


People also ask

When would you use a lock statement?

The Lock statement is used in threading, that limit the number of threads that can perform some activity or execute a portion of code at a time. Exclusive locking in threading ensures that one thread does not enter a critical section while another thread is in the critical section of the code.

Why should you avoid the lock keyword?

Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

What is the purpose of the lock keyword?

A lock is a keyword shortcut for obtaining a lock for a thread. The lock keyword makes it possible to block a section of code while working with another thread. To enter a section of code where an existing thread already exists, the other thread must wait until the previous thread's execution completes.


1 Answers

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

like image 180
Kit Avatar answered Oct 13 '22 20:10

Kit