Lock4

CSharp · Console

/Program.cs

using System;
using System.Threading;
using System.Threading.Tasks;

public static class Program
{
    private static int _Counter = 0;
	private static object _CounterLock = new object();
    
    public static void DoWork()
    {
        for (int i = 0; i < 1_000_000; i++)
        {
			bool lockWasTaken = false;
			try
			{
				Monitor.Enter(_CounterLock, ref lockWasTaken);
				_Counter++;
			}
			finally
			{
				if (lockWasTaken)
				{
					Monitor.Exit(_CounterLock);
				}
			}
        }
    }
    
    public static void Main()
    {
        Task t1 = Task.Run(DoWork);
        Task t2 = Task.Run(DoWork);
        Task.WaitAll(t1, t2);
        Console.WriteLine("{0:n0}", _Counter);
    }
}
;