コード例 #1
0
        public void WindowsPerformanceLiasonThreadTest_VerifyThreadSafe()
        {
            //// assume 4 cores
            int    numthreads   = 2;
            int    sleeptime    = 10000;
            string categoryname = CounterTestUtilities.TestCategoryName;
            //// string countername = CounterTestUtilities.TestCounterNumberOfItems64Name;
            string countername = CounterTestUtilities.TestCounterRateOfCountPerSecond64Name;

            WindowsPerformanceLiason liason = new WindowsPerformanceLiason();

            //// this warms up the counter table. otherwise every thread pays the price
            liason.CacheCounters(categoryname);
            liason.SetRawValue(categoryname, countername, 0);

            bool[]           stopflag = { false };
            Thread[]         threads  = new Thread[numthreads];
            ThreadExecutor[] allexecutorsForValidation = new ThreadExecutor[numthreads];
            for (int i = 0; i < numthreads; i++)
            {
                ThreadExecutor oneExecutor = new ThreadExecutor(liason, categoryname, countername, stopflag);
                threads[i] = new Thread(new ThreadStart(oneExecutor.CreateEvents));
                allexecutorsForValidation[i] = oneExecutor;
            }
            foreach (Thread thread in threads)
            {
                thread.Start();
            }
            Thread.Sleep(sleeptime);
            stopflag[0] = true;
            foreach (Thread thread in threads)
            {
                thread.Join();
            }
            int expected = 0;

            foreach (ThreadExecutor oneExec in allexecutorsForValidation)
            {
                expected += oneExec.ExecutionCount;
            }
            WrappedPerformanceCategory ourCat = liason.CacheCountersForCategory(categoryname);

            //// Sometimes we are off by 1 or two if we run 10 seconds. how can this be?
            Thread.Sleep(2); //// try waiting for everything to flow through
            float realNextValue = ourCat.NextValue(countername);
            int   result        = (int)ourCat.NextValue(countername);
            long  rawResult     = ourCat.GetRawValue(countername);

            //// sometimes you don't a cooked value of 0 , some glitch in reporting
            Debug.WriteLine("Threads reported {0}, Counter reported {1} updates ({2} raw) with {3} threads in {4} seconds.", expected, result, rawResult, numthreads, sleeptime);
            Assert.AreEqual(expected, (int)rawResult, "raw result didn't match");
            //// these should be exact but I've had a couple failures, not sure how that can be
            //// Assert.AreEqual(expected, result);
            Assert.AreEqual(expected, result, 2, "cooked result didn't match but raw did");
            //// this should be about 2million per thread per second on quad core macbook pro
            Assert.IsTrue(result > 20000, "expected > 20,000 but got " + result);
        }