C# InterLock保证数据一致性

Posted shidengyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        }
    }

以上是关于C# InterLock保证数据一致性的主要内容,如果未能解决你的问题,请参考以下文章

C#面试题

如何保证solr跟数据库的数据一致性

如何保证solr跟数据库的数据一致性

如何保证数据库缓存的最终一致性?

kafka数据一致性(HW只能保证副本之间的数据一致性,并不能保证数据不丢失ack或者不重复。)

C#面试题 适合新手学习参考 懂了这些你也是高手