I want to check some locking actions, and I cannot figure it out:
static void Main(string[] args) { for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => { MultithreadedMethod(); }); } Thread.Sleep(2000); Console.WriteLine(count); } static int count = 0; private static readonly int sync = 5; public static void MultithreadedMethod() { if (Monitor.TryEnter(sync)) { count++; Monitor.Exit(sync); } }
I thought this should not work due to the fact that I am performing synchronization on an integer value. The first box, then Unboxing, and I should get a System.Threading.SynchronizationLockException due to the missing root of the synchronization block (I know this refers to link types). I am not going to fool myself, even if it works for several iterations, it does not sync. Therefore, given the non-atomic property of the increment operation, I will not get deterministic results. I know it.
In fact, when I get rid of this Thead.Sleep and put Wait in Task. An exception occurs.
Task.Factory.StartNew(() => { MultithreadedMethod(); }).Wait();
I think there should be an exception: Monitor.Exit(sync)
but what catches him?
Update 1: pic added.

source share