Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor.TryEnter()

I was wondering on the Monitor Class. As far as i know all waiting threads are not FIFO. The first one that aquires the lock is not allways the first on in the waiting queue. Is this correct? Is there some way to ensure the FIFO condition?

Regards

like image 650
Mantzas Avatar asked Feb 14 '12 14:02

Mantzas


People also ask

What is the difference between Monitor and lock 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.

What is Monitor Class in c#?

The Monitor Class Provides a mechanism that synchronizes access to objects. The Monitor class is a collection of static methods that provides access to the monitor associated with a particular object, which is specified through the method's first argument. the class provide following method. Monitor.

What is lock this 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.

When should I use lock c#?

C# lock in thread The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.


1 Answers

If you are referring to a built-in way, then no. Repeatedly calling TryEnter in a loop is by definition not fair and unfortunately neither is the simple Monitor.Enter. Technically a thread could wait forever without getting the lock.

If you want absolute fairness you will need to implement it yourself using a queue to keep track of arrival order.

like image 154
Tudor Avatar answered Sep 27 '22 17:09

Tudor