public void SumTotal_Increment_IsThreadSafe() { var expectedCounts = 100000 * Environment.ProcessorCount; var counter = new SumTotal(); var cancellationTokenSource = new CancellationTokenSource(); var tasks = new List <Task>(); for (int i = 0; i < Environment.ProcessorCount; i++) { tasks.Add(Task.Factory.StartNew(() => { Thread.Sleep(1000); while (counter.Increment() <= (expectedCounts - Environment.ProcessorCount)) { if (cancellationTokenSource.IsCancellationRequested) { return; } } ; }, cancellationTokenSource.Token)); } if (!Task.WaitAll(tasks.ToArray(), 3000, cancellationTokenSource.Token)) { cancellationTokenSource.Cancel(false); Task.WaitAll(tasks.ToArray()); Assert.Fail("Counter tasks timed out."); } Assert.AreEqual(expectedCounts, counter.Value); }
public void CompositeCounter_BasicVerification() { var sumTotal = new SumTotal(); var ratePerSec = new RatePerSecond(); var meanPerSec = new MeanAverage( ratePerSec.Denominator); var medianPerSec = new MedianAverage(); var movingAverage = new MovingAverage(7); var composite = new CompositeCounter() .AddCounter(sumTotal) .AddCounter(ratePerSec) .AddCounter(meanPerSec) .AddCounter(medianPerSec) .AddCounter(movingAverage); var expectedSumTotal = 0L; var elapsedTime = new ElapsedTime(ElapsedTime.ElapsedTimeUnitType.Milliseconds); while (elapsedTime.Value <= 500) { Thread.Sleep(50); expectedSumTotal++; composite.Increment(1); } Thread.Sleep(500); Assert.AreEqual(expectedSumTotal, sumTotal.Value); Assert.AreEqual(10 /* == 1 per 50ms for 500ms */, ratePerSec.Value); Assert.AreEqual(sumTotal.Value, composite.Value); }