在C#中,我们通常使用lock关键字来实现同步,而不是像Java中的synchronized关键字
public class Counter{ private int _count; public void Increment() { lock (this) { _count++; } } public int GetCount() { return _count; }}编写一个多线程测试,以模拟并发访问同步代码。例如,使用System.Threading.Tasks.Parallel类:using System;using System.Threading.Tasks;using Xunit;public class CounterTests{ [Fact] public void TestIncrement() { const int numberOfIterations = 1000; var counter = new Counter(); Parallel.For(0, numberOfIterations, i => { counter.Increment(); }); Assert.Equal(numberOfIterations, counter.GetCount()); }}这个测试将会创建1000个并发任务,每个任务都会调用Increment方法。最后,我们断言计数器的值等于迭代次数,以确保同步代码正常工作。
注意:在实际应用中,为了避免死锁和性能问题,请确保始终使用最佳实践来实现同步代码。例如,尽量避免在长时间运行的操作中使用锁,并确保在锁定代码块之外不要引用锁定对象。


