我想测试当从多个线程调用一个方法时,没有并发问题。我模拟该方法同时调用 3 次,并在我的缓存中插入 2000 个客户,以确保不存在并发问题。
public void Should_Insert_2000_Customers_Using_Concurrency()
{
var fakeCustomers = InitCustomersFromDb();
Action insertCustomersFrom_0_to_1000 = new Action(() =>
{
Parallel.For(0, 1000, x =>
{
CustomerCache.Instance.SetCustomer(x.ToString(), fakeCustomers[0]);
});
});
Action insertCustomersFrom_1000_to_2000 = new Action(() =>
{
Parallel.For(1000, 2000, x =>
{
CustomerCache.Instance.SetCustomer(x.ToString(), fakeCustomers[0]);
});
});
Action insertCustomersFrom_0_to_2000 = new Action(() =>
{
Parallel.For(0, 2000, x =>
{
CustomerCache.Instance.SetCustomer(x.ToString(), fakeCustomers[0]);
});
});
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(insertCustomersFrom_0_to_1000));
tasks.Add(Task.Factory.StartNew(insertCustomersFrom_1000_to_2000));
tasks.Add(Task.Factory.StartNew(insertCustomersFrom_0_to_2000));
Task.WaitAll(tasks.ToArray());
var customers = CustomerCache.Instance.GetCustomers();
Assert.That(customers.Count == 2000);
}
对我运行多个同时Parallel.For
迭代CustomerCache
是否能有效地显示任何并发问题?