C# InterLock保证数据一致性

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Increment counter");
            var c = new Counter();
            var t1 = new Thread(() => TestCounter(c));
            var t2 = new Thread(() => TestCounter(c));
            var t3 = new Thread(() => TestCounter(c));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("Total Count:{0}", c.Count);
            Console.WriteLine("end Increment");

            var c1 = new CounterNoLock();

            t1 = new Thread(() => TestCounter(c));
            t2 = new Thread(() => TestCounter(c));
            t3 = new Thread(() => TestCounter(c));

            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("Total Count:{0}", c1.Count);
            Console.WriteLine("end CounterNoLock");

        }
        static void TestCounter(CounterBase c)
        {
            for (int i = 0; i < 10000; i++)
            {
                c.Increment();
                c.Decrement();
            }
        }
        class Counter : CounterBase
        {
            private int _count;
            public int Count { get { return _count; } }
            public override void Increment()
            {
                _count++;
            }
            public override void Decrement()
            {
                _count--;
            }
        }
        class CounterNoLock : CounterBase
        {
            private int _count;
            public int Count { get { return _count; } }
            public override void Increment()
            {
                Interlocked.Increment(ref _count);
            }
            public override void Decrement()
            {
                Interlocked.Decrement(ref _count);
            }
        }
        abstract class CounterBase
        {
            public abstract void Increment();
            public abstract void Decrement();
        }
    }
原文地址:https://www.cnblogs.com/shidengyun/p/5599702.html