Suppose multiple threads execute periodically the DoWork() method below. Suppose that at some point two threads begin the execution of this method almost simultaneously, so that one of the two local timestamp object is one tick larger than the other.
ICollection collection = // ...
public void DoWork()
{
DateTime timestamp = DateTime.Now;
lock(collection.SyncRoot)
{
// critical section
}
}
If the thread A is characterized by a timestamp equal to t1, while the thread B is characterized by a timestamp t2 equal to t1 + 1 tick, then the thread A will require first the access to the critical section.
How does .NET manage the access to the critical section by multiple threads? Does it put access requests in a queue, so that they are in chronological order? In other words, is the access to the critical section guaranteed according to the order of thread access requests?
There are absolutely no guarantees on order of threads execution and what thread obtains critical section first.
Note that even priority of a thread will not guarantee the order – different cores/CPUs can execute threads at different priorities at exactly the same time and any thread can reach and obtain critical section first.
Note 2: threads also can be scheduled for execution/wait at arbitrary moments of time, so the fact that 2 different operations in the same thread are next to each other does not mean they will be executed one after another without delay in between. In your case it means that thread A may be stopped as soon as it obtains time-stamp and thread B that is scheduled for execution some time later will easily get later time-stamp but gets to critical section first.