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();
}
}
{
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保证数据一致性的主要内容,如果未能解决你的问题,请参考以下文章