Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock Statement C#

Tags:

c#

locking

Say I have three threads that need access to a collection and I use a lock block around the access in each thread. The following happens...

(1) Thread 1 gets the lock on the collection
(2) Thread 2 gets blocked
(3) Thread 3 gets blocked

When Thread 1 releases the lock, who gets to take the lock next? Is it FIFO access?

Thanks

like image 445
Jason Punyon Avatar asked Feb 18 '09 20:02

Jason Punyon


People also ask

What does C# lock do?

C# Lock keyword ensures that one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section. Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.

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.

What are locks in threading?

Exclusive locking in threading ensures that one thread does not enter a critical section while another thread is in the critical section of code. If another thread attempts to enter a locked code, it will wait (block) until the object is released.

What is the difference between lock and Monitor in C#?

Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.


1 Answers

You should not care who gets the lock next.

like image 152
Amy B Avatar answered Oct 22 '22 03:10

Amy B