/// <summary> /// Test SemaphoreSlim Wait /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param> /// <param name="returnValue">The expected wait return value</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static bool RunSemaphoreSlimTest1_Wait (int initial, int maximum, object timeout, bool returnValue, Type exceptionType) { TestHarness.TestLog("Wait(" + initial + "," + maximum + "," + timeout + ")"); Exception exception = null; SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { bool result = false; if (timeout is TimeSpan) { result = semaphore.Wait((TimeSpan)timeout); } else { result = semaphore.Wait((int)timeout); } if (result != returnValue || (result && semaphore.CurrentCount != initial - 1)) { TestHarness.TestLog("Wait failed, the method returned " + result + " and expected " + returnValue); return(false); } } catch (Exception ex) { exception = ex; } // The code threw excption and it is not expected because the excyptionType param is null if (exceptionType == null && exception != null) { TestHarness.TestLog("Wait failed, the code threw an exception, and it is not supposed to."); return(false); } // Compare both exception types in case of the code threw exception if (exception != null && !Type.Equals(exception.GetType(), exceptionType)) { TestHarness.TestLog("Wait failed, Excption types do not match"); return(false); } TestHarness.TestLog("Wait succeeded"); return(true); }
/// <summary> /// Test SpinLock.TryEnter() by launching n threads, each one calls TryEnter, the succeeded threads increment /// a counter variable and failed threads increment failed variable, count + failed must be equal to n /// </summary> /// <param name="threadsCount">Number of threads that call enter/exit</param> /// <returns>True if succeeded, false otherwise</returns> private static bool RunSpinLockTest1_TryEnter(int threadsCount, bool enableThreadIDs) { TestHarness.TestLog("SpinLock.TryEnter(" + threadsCount + " threads)"); Thread[] threads = new Thread[threadsCount]; SpinLock slock = new SpinLock(enableThreadIDs); int succeeded = 0; int failed = 0; // Run threads for (int i = 0; i < threadsCount; i++) { threads[i] = new Thread(delegate() { bool lockTaken = false; slock.TryEnter(ref lockTaken); if (lockTaken) { // Increment succeeded counter Interlocked.Increment(ref succeeded); slock.Exit(); } else { // Increment failed counter Interlocked.Increment(ref failed); } }); threads[i].Start(); } // Wait all threads for (int i = 0; i < threadsCount; i++) { threads[i].Join(); } // succeeded + failed must be equal to the threads count. if (succeeded + failed != threadsCount) { TestHarness.TestLog("SpinLock.TryEnter() failed, actual count: " + (succeeded + failed) + " expected :" + threadsCount); return(false); } TestHarness.TestLog("SpinLock.TryEnter() passed."); return(true); }
public static bool Test() { TestHarness.TestLog("* Tree.Test(treedepth={0})", treedepth); Tree t = Generate(treedepth); int s0 = t.SeqSum(); int s1 = t.ParSum(); if (s0 != s1) { TestHarness.TestLog(" > failed: seq sum = {0}, but par sum = {1}", s0, s1); return(false); } return(true); }
private static bool RunConcurrentBagTest7_BugFix575975() { TestHarness.TestLog("* RunConcurrentBagTest7_BugFix575975"); BlockingCollection <int> bc = new BlockingCollection <int>(new ConcurrentBag <int>()); bool succeeded = true; Thread[] threads = new Thread[4]; for (int t = 0; t < threads.Length; t++) { threads[t] = new Thread((obj) => { int index = (int)obj; for (int i = 0; i < 100000; i++) { if (index < threads.Length / 2) { for (int j = 0; j < 1000; j++) { Math.Min(j, j - 1); } bc.Add(i); } else { try { bc.Take(); } catch // Take must not fail { succeeded = false; break; } } } }); threads[t].Start(t); } for (int t = 0; t < threads.Length; t++) { threads[t].Join(); } TestHarness.TestLog("BugFix575975 {0}", succeeded ? "succeeded" : "failed"); return(succeeded); }
private static bool RunDictionaryTest_BugFix669376() { TestHarness.TestLog("* RunDictionaryTest_BugFix669376"); var cd = new ConcurrentDictionary <string, int>(StringComparer.OrdinalIgnoreCase); cd["test"] = 10; if (cd.ContainsKey("TEST")) { return(true); } else { TestHarness.TestLog(" > Customized comparer didn't work"); return(false); } }
/// <summary> /// Test bag addition /// </summary> /// <param name="threadsCount"></param> /// <param name="itemsPerThread"></param> /// <returns>True if succeeded, false otherwise</returns> private static bool RunConcurrentBagTest2_Add(int threadsCount, int itemsPerThread) { TestHarness.TestLog("* RunConcurrentBagTest1_Add(" + threadsCount + "," + itemsPerThread + ")"); int failures = 0; ConcurrentBag <int> bag = new ConcurrentBag <int>(); Thread[] threads = new Thread[threadsCount]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(() => { for (int j = 0; j < itemsPerThread; j++) { try { bag.Add(j); } catch { Interlocked.Increment(ref failures); } } }); threads[i].Start(); } for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } if (failures > 0) { TestHarness.TestLog("Add failed, " + failures + " threads threw unexpected exceptions"); return(false); } if (bag.Count != itemsPerThread * threadsCount) { TestHarness.TestLog("Add failed, the bag count doesn't match the expected count"); return(false); } TestHarness.TestLog("Add succeeded"); return(true); }
/// <summary> /// Build the PFX, dev unit tests and XML for PFX /// </summary> /// <returns>True if succeeded, false otherwise</returns> private static bool BuildPFX() { TestHarness.TestLog("Build PFX 3.5 source code"); Process p = new Process(); string msbuildPath = p.StartInfo.EnvironmentVariables["_NTBINDIR"] + "\\tools\\x86\\managed\\WinFx\\v3.5\\msbuild.exe"; p.StartInfo.FileName = msbuildPath; p.StartInfo.Arguments = "ParallelExtensions_3_5.csproj"; p.StartInfo.WorkingDirectory = Environment.GetEnvironmentVariable("_NT_SOURCE_PATH") + "\\qa\\pfx\\ParallelExtensions_3_5"; List <string> srcBuildErrors, testBuildErrors, xmlBuildErrors; srcBuildErrors = RunProcess(p); if (srcBuildErrors != null) { SaveErrors(srcBuildErrors, "srcBuild.err.txt"); TestHarness.TestLog("Build source failed, check {0} file", "srcBuild.err.txt"); return(false); } TestHarness.TestLog("Build PFX 3.5 dev unit tests"); p.StartInfo.Arguments = "DevUnitTests.csproj"; testBuildErrors = RunProcess(p); if (testBuildErrors != null) { SaveErrors(testBuildErrors, "testsBuild.err.txt"); TestHarness.TestLog("Build tests failed, check {0} file", "testsBuild.err.txt"); return(false); } TestHarness.TestLog("Build PFX 3.5 Xml docs"); p.StartInfo.Arguments = "ParallelExtensions_3_5.csproj"; p.StartInfo.EnvironmentVariables.Add("Enable_PFX_Docs", "1"); xmlBuildErrors = RunProcess(p); if (xmlBuildErrors != null) { SaveErrors(xmlBuildErrors, "xmlBuild.err.txt"); TestHarness.TestLog("Build XML failed, check {0} file", "xmlBuild.err.txt"); // Even if the XML check fails, we will let the test pass. return(true); } return(true); }
private static bool RunDictionaryTest_Remove3() { TestHarness.TestLog("* RunDictionaryTest_Remove3()"); ConcurrentDictionary <int, int> dict = new ConcurrentDictionary <int, int>(); dict[99] = -99; ICollection <KeyValuePair <int, int> > col = dict; // Make sure we cannot "remove" a key/value pair which is not in the dictionary for (int i = 0; i < 1000; i++) { if (i != 99) { if (col.Remove(new KeyValuePair <int, int>(i, -99)) || col.Remove(new KeyValuePair <int, int>(99, -i))) { TestHarness.TestLog(" > Removed a key/value pair which was not supposed to be in the dictionary."); return(false); } } } // Can we remove a key/value pair successfully? if (!col.Remove(new KeyValuePair <int, int>(99, -99))) { TestHarness.TestLog(" > Failed to remove a key/value pair which was supposed to be in the dictionary."); return(false); } // Make sure the key/value pair is gone if (col.Remove(new KeyValuePair <int, int>(99, -99))) { TestHarness.TestLog(" > Removed a key/value pair which was not supposed to be in the dictionary."); return(false); } // And that the dictionary is empty. We will check the count in a few different ways: if (dict.Count != 0 || dict.ToArray().Count() != 0 || dict.ToList().Count() != 0) { TestHarness.TestLog(" > Incorrect count of elements reported for the dictionary."); return(false); } return(true); }
/// <summary> /// Test Dispose /// </summary> /// <returns>Tru if the test succeeded, false otherwise</returns> private static bool RunBarrierTest6_Dispose() { TestHarness.TestLog("*RunBarrierTest6_Dispose"); Barrier b = new Barrier(1); b.Dispose(); try { b.SignalAndWait(); } catch (ObjectDisposedException) { TestHarness.TestLog("Dispose succeeded"); return(true); } TestHarness.TestLog("Cancel failed, SignalAndWait didn't throw exceptions after Dispose."); return(false); }
// Just validates the stack correctly reports that it's empty. private static bool RunConcurrentStackTest0_Empty(int count) { TestHarness.TestLog("* RunConcurrentStackTest0_Empty()"); ConcurrentStack <int> s = new ConcurrentStack <int>(); for (int i = 0; i < count; i++) { s.Push(i); } bool isEmpty = s.IsEmpty; int sawCount = s.Count; TestHarness.TestLog(" > IsEmpty={0} (expect {1}), Count={2} (expect {3})", isEmpty, count == 0, sawCount, count); return(isEmpty == (count == 0) && sawCount == count); }
// Just validates the queue correctly reports that it's empty. private static bool RunConcurrentQueueTest0_Empty(int count) { TestHarness.TestLog("* RunConcurrentQueueTest0_Empty()"); ConcurrentQueue <int> q = new ConcurrentQueue <int>(); for (int i = 0; i < count; i++) { q.Enqueue(i); } bool isEmpty = q.IsEmpty; int sawCount = q.Count; TestHarness.TestLog(" > IsEmpty={0} (expect {1}), Count={2} (expect {3})", isEmpty, count == 0, sawCount, count); return(isEmpty == (count == 0) && sawCount == count); }
/// <summary> /// Run all SpinLock tests /// </summary> /// <returns>True if all tests passed, false if at least one test failed</returns> internal static bool RunSpinLockTests() { // boolean variable that represent the rest result, it is anded with each unit test // result, must be true after calling all tests bool passed = true; for (int i = 0; i < 2; i++) { bool b; if (i == 0) { TestHarness.TestLog("NO THREAD IDS -- new SpinLock(true)"); b = true; } else { TestHarness.TestLog("WITH THREAD IDS -- new SpinLock(false)"); b = false; } TestHarness.TestLog("Testing Enter()"); passed &= RunSpinLockTest0_Enter(2, b); passed &= RunSpinLockTest0_Enter(128, b); passed &= RunSpinLockTest0_Enter(256, b); TestHarness.TestLog("Testing TryEnter()"); passed &= RunSpinLockTest1_TryEnter(2, b); passed &= RunSpinLockTest1_TryEnter(128, b); passed &= RunSpinLockTest1_TryEnter(256, b); TestHarness.TestLog("Testing TryEnter(TimeSpan)"); passed &= RunSpinLockTest2_TryEnter(2, b); passed &= RunSpinLockTest2_TryEnter(128, b); passed &= RunSpinLockTest2_TryEnter(256, b); TestHarness.TestLog("Testing Invalid cases for TryEnter()"); passed &= RunSpinLockTest3_TryEnter(b); TestHarness.TestLog("Testing Exit()"); passed &= RunSpinLockTest4_Exit(b); } return(passed); }
internal static bool RunTests() { LeftOperator[] leftOps = new LeftOperator[] { new LeftOperator(MakeCast, true), new LeftOperator(MakeConcat, true), new LeftOperator(MakeDefaultIfEmpty, true), new LeftOperator(MakeDistinct, false), new LeftOperator(MakeExcept, false), new LeftOperator(MakeGroupBy, false), new LeftOperator(MakeGroupJoin, false), new LeftOperator(MakeIntersect, false), new LeftOperator(MakeJoin, false), new LeftOperator(MakeOfType, true), new LeftOperator(MakeOrderBy, true), new LeftOperator(MakeOrderByThenBy, true), new LeftOperator(MakeReverse, true), new LeftOperator(MakeSelect, true), new LeftOperator(MakeSelectMany, false), new LeftOperator(MakeSkip, true), new LeftOperator(MakeSkipWhile, true), new LeftOperator(MakeSkipWhileIndexed, true), new LeftOperator(MakeTakeWhile, true), new LeftOperator(MakeTakeWhileIndexed, true), new LeftOperator(MakeUnion, false), new LeftOperator(MakeWhere, true), new LeftOperator(MakeWhereIndexed, true), new LeftOperator(MakeZip, true) }; TestTracker result = new TestTracker(); foreach (bool orderPreserved in new bool[] { true, false }) { foreach (LeftOperator leftOp in leftOps) { String operatorName = leftOp.OperatorName; TestHarness.TestLog("Left Operator={0}, Options={1}", operatorName, orderPreserved); ParallelQuery <int> q = leftOp.LeftOperatorFactory(orderPreserved); RunAllTests(result, q, orderPreserved, operatorName, leftOp.OrderDefined); } } return(result.Passed); }
private static bool CancellationSequentialElementAt() { TestHarness.TestLog("* PlinqCancellationTests.CancellationSequentialElementAt()"); IEnumerable <int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); bool success = false; Task task = Task.Factory.StartNew( () => { try { int res = src.AsParallel() .WithCancellation(tokenSrc.Token) .Where(x => true) .TakeWhile(x => true) .ElementAt(int.MaxValue - 1); TestHarness.TestLog(" > Failed: OperationCanceledException was not caught."); } catch (OperationCanceledException oce) { if (OCEHelper.ExtractCT(oce) == tokenSrc.Token) { success = true; } else { TestHarness.TestLog(" > Failed: Wrong cancellation token."); } } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Thread.Sleep(100); tokenSrc.Cancel(); task.Wait(); return(success); }
private static bool RunJoinPlusWhereTest1(int leftSize, int rightSize, int loops) { TestHarness.TestLog("RunJoinPlusWhereTest1({0}, {1}, {2})", leftSize, rightSize, loops); int[] left = new int[leftSize]; int[] right = new int[rightSize]; for (int i = 0; i < left.Length; i++) { left[i] = i; } for (int i = 0; i < right.Length; i++) { right[i] = i * right.Length; } Func <int, int> identityKeySelector = delegate(int x) { return(x); }; IEnumerable <Pair> seqQuery = Enumerable.Join <int, int, int, Pair>( Enumerable.Where <int>(left, delegate(int x) { return((x % 2) == 0); }), right, identityKeySelector, identityKeySelector, delegate(int x, int y) { return(new Pair(x, y)); }); IEnumerable <Pair> parQuery = left.AsParallel().Where <int>(delegate(int x) { return((x % 2) == 0); }) .Join <int, int, int, Pair>(right.AsParallel(), identityKeySelector, identityKeySelector, delegate(int x, int y) { return(new Pair(x, y)); }); PerfHelpers.DrivePerfComparison( delegate { foreach (Pair p in seqQuery) { // Calc the log (to simulate some work): Math.Log(p.x, p.y); } }, delegate { foreach (Pair p in parQuery) { // Calc the log (to simulate some work): Math.Log(p.x, p.y); } }, loops); return(true); }
/// <summary> /// Ensures the post phase action throws if Dispose,SignalAndWait and Add/Remove participants called from it. /// </summary> private static bool EnsurePostPhaseThrew(Barrier barrier) { try { barrier.SignalAndWait(); TestHarness.TestLog("PostPhaseException failed, Postphase action didn't throw."); return(false); } catch (BarrierPostPhaseException ex) { if (!ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) { TestHarness.TestLog("PostPhaseException failed, Postphase action didn't throw the correct exception."); return(false); } } return(true); }
/// <summary>Tests for the Initialized property.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> private static bool RunThreadLocalTest3_IsValueCreated() { TestHarness.TestLog("* RunThreadLocalTest6_Initialized()"); ThreadLocal <string> tlocal = new ThreadLocal <string>(() => "Test"); if (tlocal.IsValueCreated) { TestHarness.TestLog(" > test failed - expected ThreadLocal to be uninitialized."); return(false); } string temp = tlocal.Value; if (!tlocal.IsValueCreated) { TestHarness.TestLog(" > test failed - expected ThreadLocal to be initialized."); return(false); } return(true); }
/// <summary> /// Heavily exercises OrderBy, but only throws one user delegate exception to simulate an occassional failure. /// /// </summary> internal static bool OrderBy_OnlyOneException(int range) { TestHarness.TestLog(String.Format("* OrderBy_OnlyOneException({0})", range)); bool success = true; Console.Write(" DOP: "); for (int dop = 1; dop <= 30; dop++) { Console.Write(dop.ToString("00") + ".. "); if (dop % 10 == 0) { Console.Write(Environment.NewLine + " "); } int indexForException = range / (2 * dop); // eg 1000 items on 4-core, throws on item 125. AggregateException caughtAggregateException = null; try { var query = Enumerable.Range(0, range) .AsParallel().WithDegreeOfParallelism(dop) .OrderBy(i => { UserDelegateException.ThrowIf(i == indexForException); return(i); } ); foreach (int i in query) { } } catch (AggregateException e) { caughtAggregateException = e; } success &= (caughtAggregateException != null); success &= (caughtAggregateException.InnerExceptions.Count == 1); } Console.WriteLine(); return(success); }
/// <summary> /// Zip with ordering on showed issues, but it was due to the ordering component. /// This is included as a regression test for that particular repro. /// </summary> /// <param name="range"></param> /// <returns></returns> internal static bool ZipAndOrdering(int range) { TestHarness.TestLog(String.Format("* ZipAndOrdering({0})", range)); bool success = true; Console.Write(" DOP: "); for (int dop = 1; dop <= 30; dop++) { Console.Write(dop.ToString("00") + ".. "); if (dop % 10 == 0) { Console.Write(Environment.NewLine + " "); } AggregateException ex = null; try { var enum1 = Enumerable.Range(1, range); var enum2 = Enumerable.Repeat(1, range * 2); var query1 = enum1 .AsParallel() .AsOrdered().WithDegreeOfParallelism(dop) .Zip(enum2.AsParallel().AsOrdered(), (a, b) => UserDelegateException.Throw <int, int, int>(a, b)); var output = query1.ToArray(); } catch (AggregateException ae) { ex = ae; } success &= (ex != null); success &= (false == PlinqDelegateExceptionHelpers.AggregateExceptionContains(ex, typeof(OperationCanceledException))); success &= (PlinqDelegateExceptionHelpers.AggregateExceptionContains(ex, typeof(UserDelegateException))); } Console.WriteLine(); return(success); }
private static bool CancellationTokenTest_Sorting_ToArray() { bool passed = true; TestHarness.TestLog("* PlinqCancellationTests.CancellationTokenTest_Sorting_ToArray()"); int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem( (arg) => { Thread.Sleep(500); tokenSource.Cancel(); }); OperationCanceledException caughtException = null; try { // This query should run for at least a few seconds due to the sleeps in the select-delegate var query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { Thread.Sleep(1); return(i); }); query.ToArray(); } catch (OperationCanceledException ex) { caughtException = ex; } passed &= TestHarnessAssert.IsNotNull(caughtException, "An OCE should be thrown"); passed &= TestHarnessAssert.AreEqual(tokenSource.Token, OCEHelper.ExtractCT(caughtException), "The OCE should reference the external token."); return(passed); }
private static bool RunThreadLocalTest5_Dispose() { TestHarness.TestLog("* RunThreadLocalTest5_Dispose()"); ThreadLocal <string> tl = new ThreadLocal <string>(() => "dispose test"); string value = tl.Value; tl.Dispose(); if (!TestHarnessAssert.EnsureExceptionThrown(() => { string tmp = tl.Value; }, typeof(ObjectDisposedException), "The Value property of the disposed ThreadLocal object should throw ODE")) { return(false); } if (!TestHarnessAssert.EnsureExceptionThrown(() => { bool tmp = tl.IsValueCreated; }, typeof(ObjectDisposedException), "The IsValueCreated property of the disposed ThreadLocal object should throw ODE")) { return(false); } if (!TestHarnessAssert.EnsureExceptionThrown(() => { string tmp = tl.ToString(); }, typeof(ObjectDisposedException), "The ToString method of the disposed ThreadLocal object should throw ODE")) { return(false); } // test recycling the combination index; tl = new ThreadLocal <string>(() => null); if (tl.IsValueCreated) { TestHarness.TestLog("* Filed, reusing the same index kept the old value and didn't use the new value."); return(false); } if (tl.Value != null) { TestHarness.TestLog("* Filed, reusing the same index kept the old value and didn't use the new value."); return(false); } return(true); }
private static bool RunPartitionerStaticTest_EmptyPartitions() { TestHarness.TestLog("RunPartitionerStaticTest_EmptyPartitions: partitioning an empty list into 4 partitions"); int[] data = new int[0]; bool passed = true; // Test ArgumentNullException of source data OrderablePartitioner <int> partitioner; for (int algorithm = 0; algorithm < 5; algorithm++) { partitioner = PartitioningWithAlgorithm <int>(data, algorithm); //test GetOrderablePartitions var partitions1 = partitioner.GetOrderablePartitions(4); //verify all partitions are empty for (int i = 0; i < 4; i++) { passed &= (!partitions1[i].MoveNext()); } //test GetOrderableDynamicPartitions try { var partitions2 = partitioner.GetOrderableDynamicPartitions(); //verify all partitions are empty var newPartition = partitions2.GetEnumerator(); passed &= (!newPartition.MoveNext()); } catch (NotSupportedException) { Debug.Assert(IsStaticPartition(algorithm)); } } if (!passed) { TestHarness.TestLog("failed: resulting partitions not empty as supposed to"); } return(passed); }
/// <summary> /// Test SignalAndWait sequential /// </summary> /// <param name="initialCount">The initial barrier participants</param> /// <param name="timeout">SignalAndWait timeout</param> /// <param name="result">Expected return value</param> /// <param name="exceptionType"></param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static bool RunBarrierTest2_SignalAndWait(int initialCount, TimeSpan timeout, bool result, Type exceptionType) { TestHarness.TestLog("SignalAndWait(" + initialCount + "," + timeout + ")"); Barrier b = new Barrier(initialCount); Exception exception = null; try { if (b.SignalAndWait(timeout) != result) { TestHarness.TestLog("SignalAndWait failed, return value doesn't match the expected value"); return(false); } if (result && b.CurrentPhaseNumber != 1) { TestHarness.TestLog("SignalAndWait failed, CurrentPhaseNumber has not been incremented after SignalAndWait"); return(false); } if (result && b.ParticipantsRemaining != b.ParticipantCount) { TestHarness.TestLog("SignalAndWait failed, ParticipantsRemaming does not equal the total participants"); return(false); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { TestHarness.TestLog("SignalAndWait failed, unexpected exception has been thrown."); return(false); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { TestHarness.TestLog("SignalAndWait failed, exceptions types do not match."); return(false); } TestHarness.TestLog("SignalAndWait succeeded"); return(true); }
/// <summary>Tests for the Initialized property.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> private static bool RunLazyTest6_IsValueCreated() { TestHarness.TestLog("* RunLazyTest6_Initialized()"); Lazy <string> lazy = new Lazy <string>(() => "Test"); if (lazy.IsValueCreated) { TestHarness.TestLog(" > test failed - expected lazy to be uninitialized."); return(false); } string temp = lazy.Value; if (!lazy.IsValueCreated) { TestHarness.TestLog(" > test failed - expected lazy to be initialized."); return(false); } return(true); }
// Just validates clearing the stack's contents. private static bool RunConcurrentStackTest3_Clear(int count) { TestHarness.TestLog("* RunConcurrentStackTest3_Clear()"); ConcurrentStack <int> s = new ConcurrentStack <int>(); for (int i = 0; i < count; i++) { s.Push(i); } s.Clear(); bool isEmpty = s.IsEmpty; int sawCount = s.Count; TestHarness.TestLog(" > IsEmpty={0}, Count={1}", isEmpty, sawCount); return(isEmpty && sawCount == 0); }
// Just validates enumerating the stack. private static bool RunConcurrentQueueTest4_Enumerator(int count) { TestHarness.TestLog("* RunConcurrentQueueTest4_Enumerator()"); ConcurrentQueue <int> s = new ConcurrentQueue <int>(); for (int i = 0; i < count; i++) { s.Enqueue(i); } // Test enumerator. int j = 0; foreach (int x in s) { // Clear the stack to ensure concurrent modifications are dealt w/. if (x == count - 1) { int e; while (s.TryDequeue(out e)) { ; } } if (x != j) { TestHarness.TestLog(" > expected #{0}, but saw #{1}", j, x); return(false); } j++; } if (j != count) { TestHarness.TestLog(" > did not enumerate all elements in the stack"); return(false); } return(true); }
/// <summary> /// Runs all the unit tests /// </summary> /// <returns>True if all tests succeeded, false if one or more tests failed</returns> internal static bool RunBarrierTests() { bool passed = true; TestHarness.TestLog("Testing Barrier Constructor"); passed &= RunBarrierTest1_ctor(10, null); passed &= RunBarrierTest1_ctor(0, null); passed &= RunBarrierTest1_ctor(-1, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest1_ctor(int.MaxValue, typeof(ArgumentOutOfRangeException)); TestHarness.TestLog("Testing Barrier SignalAndWait"); passed &= RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -1), true, null); passed &= RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -2), false, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest2_SignalAndWait(5, new TimeSpan(0, 0, 0, 0, 100), false, null); passed &= RunBarrierTest2_SignalAndWait(5, new TimeSpan(0), false, null); TestHarness.TestLog("Testing Barrier parallel SignalAndWait"); passed &= RunBarrierTest3_SignalAndWait(3); TestHarness.TestLog("Testing Barrier AddParticipants"); passed &= RunBarrierTest4_AddParticipants(0, 1, null); passed &= RunBarrierTest4_AddParticipants(5, 3, null); passed &= RunBarrierTest4_AddParticipants(0, 0, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest4_AddParticipants(2, -1, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest4_AddParticipants(0x00007FFF, 1, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest4_AddParticipants(100, int.MaxValue, typeof(ArgumentOutOfRangeException)); // bug#714977 TestHarness.TestLog("Testing Barrier RemoveParticipants"); passed &= RunBarrierTest5_RemoveParticipants(1, 1, null); passed &= RunBarrierTest5_RemoveParticipants(10, 7, null); passed &= RunBarrierTest5_RemoveParticipants(10, 0, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest5_RemoveParticipants(1, -1, typeof(ArgumentOutOfRangeException)); passed &= RunBarrierTest5_RemoveParticipants(5, 6, typeof(ArgumentOutOfRangeException)); TestHarness.TestLog("Testing Barrier Dispose"); passed &= RunBarrierTest6_Dispose(); passed &= RunBarrierTest7_Bug603035(); passed &= RunBarrierTest8_PostPhaseException(); passed &= RunBarrierTest9_PostPhaseException(); return(passed); }
/// <summary> /// Another basic test for a query that throws user delegate exceptions /// </summary> /// <returns></returns> internal static bool SelectJoin() { TestHarness.TestLog("* SelectJoin()"); Exception caughtAggregateException = null; try { var query = new int[] { 1, 2, 3 }.AsParallel() .Select(i => UserDelegateException.Throw <int, int>(i)) .Join(new int[] { 1 }.AsParallel(), i => i, j => j, (i, j) => 0); foreach (var x in query) { } } catch (AggregateException e) { caughtAggregateException = e; } return(caughtAggregateException != null); }
// Issue identified in Bug 543310 and also tracked as task 'channel cancellation' // Use of the async channel can block both the consumer and producer threads.. before the cancellation work // these had no means of being awoken. // // However, only the producers need to wake up on cancellation as the consumer // will wake up once all the producers have gone away (via AsynchronousOneToOneChannel.SetDone()) // // To specifically verify this test, we want to know that the Async channels were blocked in TryEnqueChunk before Dispose() is called // -> this was verified manually, but is not simple to automate private static bool BugFix543310_ChannelCancellation_ProducerBlocked() { bool passed = true; TestHarness.TestLog("* PlinqCancellationTests.BugFix543310_ChannelCancellation_ProducerBlocked()"); Console.Write(" Query running (should be few seconds max).."); var query1 = Enumerable.Range(0, 100000000) //provide 100million elements to ensure all the cores get >64K ints. Good up to 1600cores .AsParallel() .Select(x => x); var enumerator1 = query1.GetEnumerator(); enumerator1.MoveNext(); Thread.Sleep(1000); // give the pipelining time to fill up some buffers. enumerator1.MoveNext(); enumerator1.Dispose(); //can potentially hang Console.WriteLine(" Done (success)."); return(passed); }
/// <summary> /// Verifies that a pipelining merge does not create any helper tasks in the DOP=1 case. /// </summary> private static bool SequentialPipeliningTest(int inputSize, bool buffered, bool ordered) { TestHarness.TestLog("SequentialPipeliningTest: inputSize={0}, buffered={1}, ordered={2}", inputSize, buffered, ordered); ParallelMergeOptions merge = buffered ? ParallelMergeOptions.AutoBuffered : ParallelMergeOptions.NotBuffered; bool success = true; int consumerThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; System.Linq.ParallelQuery <int> src = System.Linq.ParallelEnumerable.Range(0, inputSize); if (ordered) { src = src.AsOrdered(); } src = src.WithMergeOptions(merge) .WithDegreeOfParallelism(1) .Select( x => { if (System.Threading.Thread.CurrentThread.ManagedThreadId != consumerThreadId) { success = false; } return(x); }); foreach (var x in src) { } if (!success) { TestHarness.TestLog("> The producer task executed on a wrong thread."); return(false); } return(true); }