我想測試從多個線程調用某個方法時,沒有併發問題。我模擬該方法被同時調用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);
}
將在運行對我CustomerCache
多個同時Parallel.For
迭代是在表現出任何的併發問題是否有效?
那麼你的問題是什麼?你是否要求進行代碼審查? – slugster 2012-07-09 09:23:03
我想知道這些測試是否適合測試多線程。或者,如果它沒用... – Florian 2012-07-09 09:30:24
Parallel.For是異步的,所以你使用更多的線程,取決於你有多少個CPU /核心。 – Maarten 2012-07-09 09:31:39