コード例 #1
0
ファイル: SchedulerProxy.cs プロジェクト: hindlemail/mono
		public void ParticipateUntil (Task task)
		{
			ManualResetEventSlim evt = new ManualResetEventSlim (false);
			task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously);

			ParticipateUntil (evt, -1);
		}
コード例 #2
0
        public static void RunManualResetEventSlimTest2_TimeoutWait()
        {
            for (int i = 0; i < 2; i++)
            {
                ManualResetEventSlim ev = null;
                if (i == 0) // no custom SpinCount
                    ev = new ManualResetEventSlim(false);
                else
                    ev = new ManualResetEventSlim(false, 500);

                if (ev.Wait(0))
                {
                    Assert.True(false, string.Format("RunManualResetEventSlimTest2_TimeoutWait: FAILED  > ev.Wait(0) returned true -- event isn't set  ({0})", ev.IsSet));
                }

                if (ev.Wait(100))
                {
                    Assert.True(false, string.Format("RunManualResetEventSlimTest2_TimeoutWait: FAILED  > ev.Wait(100) returned true -- event isn't set  ({0})", ev.IsSet));
                }

                if (ev.Wait(TimeSpan.FromMilliseconds(100)))
                {
                    Assert.True(false, string.Format("RunManualResetEventSlimTest2_TimeoutWait: FAILED  > ev.Wait(0) returned true -- event isn't set  ({0})", ev.IsSet));
                }

                ev.Dispose();
            }
        }
コード例 #3
0
        // Validates init, set, reset state transitions.
        private static void RunManualResetEventSlimTest0_StateTrans(bool init)
        {
            ManualResetEventSlim ev = new ManualResetEventSlim(init);
            if (ev.IsSet != init)
            {
                Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                Assert.True(false, string.Format("  > FAILED.  expected IsSet=={0}, but it's {1}", init, ev.IsSet));
            }

            for (int i = 0; i < 50; i++)
            {
                ev.Set();
                if (!ev.IsSet)
                {
                    Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                    Assert.True(false, string.Format("  > FAILED.  expected IsSet, but it's false"));
                }

                ev.Reset();
                if (ev.IsSet)
                {
                    Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);
                    Assert.True(false, string.Format("  > FAILED.  expected !IsSet, but it's true"));
                }
            }
        }
コード例 #4
0
ファイル: CountdownEvent.cs プロジェクト: gezidan/ZYSOCKET
		public CountdownEvent (int initialCount)
		{
			if (initialCount < 0)
				throw new ArgumentOutOfRangeException ("initialCount");

			evt = new ManualResetEventSlim (initialCount == 0);
			this.initial = this.initialCount = initialCount;
		}
コード例 #5
0
ファイル: SchedulerProxy.cs プロジェクト: hindlemail/mono
		public bool ParticipateUntil (Task task, ManualResetEventSlim evt, int millisecondsTimeout)
		{
			bool fromPredicate = true;
			task.ContinueWith (_ => { fromPredicate = false; evt.Set (); }, TaskContinuationOptions.ExecuteSynchronously);

			ParticipateUntil (evt, millisecondsTimeout);

			return fromPredicate;
		}
コード例 #6
0
ファイル: Scheduler.cs プロジェクト: hindlemail/mono
		public bool ParticipateUntil (Task task, ManualResetEventSlim evt, int millisecondsTimeout)
		{
			if (task.IsCompleted)
				return false;

			bool isFromPredicate = true;
			task.ContinueWith (_ => { isFromPredicate = false; evt.Set (); }, TaskContinuationOptions.ExecuteSynchronously);
			
			ParticipateUntilInternal (task, evt, millisecondsTimeout);

			return isFromPredicate;
		}
コード例 #7
0
ファイル: Scheduler.cs プロジェクト: koush/mono
		internal override void ParticipateUntil (Task task)
		{
			if (task.IsCompleted)
				return;

			ManualResetEventSlim evt = new ManualResetEventSlim (false);
			task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously);
			if (evt.IsSet || task.IsCompleted)
				return;
			
			ParticipateUntilInternal (task, evt, -1);
		}
コード例 #8
0
        // Validates init, set, reset state transitions.
        private static void RunManualResetEventSlimTest0_StateTrans(bool init)
        {
            ManualResetEventSlim ev = new ManualResetEventSlim(init);
            Assert.Equal(init, ev.IsSet);

            for (int i = 0; i < 50; i++)
            {
                ev.Set();
                Assert.True(ev.IsSet);

                ev.Reset();
                Assert.False(ev.IsSet);
            }
        }
コード例 #9
0
ファイル: TaskAwaiterTests.cs プロジェクト: ESgarbi/corefx
        public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                // Create a context that tracks operations, and set it as current
                var validateCtx = new ValidateCorrectContextSynchronizationContext();
                Assert.Equal(0, validateCtx.PostCount);
                SynchronizationContext.SetSynchronizationContext(validateCtx);

                // Create a not-completed task and get an awaiter for it
                var mres = new ManualResetEventSlim();
                var tcs = new TaskCompletionSource<object>();

                // Hook up a callback
                bool postedInContext = false;
                Action callback = () =>
                {
                    postedInContext = ValidateCorrectContextSynchronizationContext.IsPostedInContext;
                    mres.Set();
                };
                if (generic)
                {
                    if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    else tcs.Task.GetAwaiter().OnCompleted(callback);
                }
                else
                {
                    if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                }
                Assert.False(mres.IsSet, "Callback should not yet have run.");

                // Complete the task in another context and wait for the callback to run
                Task.Run(() => tcs.SetResult(null));
                mres.Wait();

                // Validate the callback ran and in the correct context
                bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
                Assert.Equal(shouldHavePosted, postedInContext);
            }
            finally
            {
                // Reset back to the original context
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
コード例 #10
0
        public static void RunManualResetEventSlimTest2_TimeoutWait()
        {
            for (int i = 0; i < 2; i++)
            {
                ManualResetEventSlim ev = null;
                if (i == 0) // no custom SpinCount
                    ev = new ManualResetEventSlim(false);
                else
                    ev = new ManualResetEventSlim(false, 500);
                Assert.False(ev.Wait(0));
                Assert.False(ev.Wait(100));
                Assert.False(ev.Wait(TimeSpan.FromMilliseconds(100)));

                ev.Dispose();
            }
        }
コード例 #11
0
        public static void CancelBeforeWait()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim();
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);

            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            mres.Dispose();
        }
コード例 #12
0
        public static void RunManualResetEventSlimTest1_SimpleWait()
        {
            ManualResetEventSlim ev1 = new ManualResetEventSlim(false);
            ManualResetEventSlim ev2 = new ManualResetEventSlim(false);
            ManualResetEventSlim ev3 = new ManualResetEventSlim(false);

            Task.Run(delegate
            {
                ev2.Set();
                ev1.Wait();
                ev3.Set();
            });

            ev2.Wait();
            //Thread.Sleep(100);
            ev1.Set();
            ev3.Wait();
        }
コード例 #13
0
        public static void CancelAfterWait()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            ManualResetEventSlim mres = new ManualResetEventSlim();

            Task.Run(
                () =>
                {
                    for (int i = 0; i < 400; i++) ;
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            EnsureOperationCanceledExceptionThrown(
               () => mres.Wait(cancellationToken), cancellationToken,
               "CancelBeforeWait:  An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
        }
コード例 #14
0
ファイル: EventSlots.cs プロジェクト: nestalk/mono
		public ManualEventSlot (ManualResetEventSlim evt)
		{
			this.evt = evt;
		}
コード例 #15
0
ファイル: ThreadLocalTests.cs プロジェクト: noahfalk/corefx
 public SetMreOnFinalize(ManualResetEventSlim mres)
 {
     _mres = mres;
 }
コード例 #16
0
ファイル: ThreadLocalTests.cs プロジェクト: noahfalk/corefx
        public static void RunThreadLocalTest8_Values_NegativeCases()
        {
            // Test that Dispose works and that objects are released on dispose
            {
                var mres = new ManualResetEventSlim();
                RunThreadLocalTest8Helper(mres);

                SpinWait.SpinUntil(() =>
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    return mres.IsSet;
                }, 1000);

                Assert.True(mres.IsSet, "RunThreadLocalTest8_Values: Expected thread local to release the object and for it to be finalized");
            }

            // Test that Values property throws an exception unless true was passed into the constructor
            {
                ThreadLocal<int> t = new ThreadLocal<int>();
                t.Value = 5;
                Exception exceptionCaught = null;
                try
                {
                    var randomValue = t.Values.Count;
                }
                catch (Exception ex)
                {
                    exceptionCaught = ex;
                }

                Assert.True(exceptionCaught != null, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. No exception was thrown.");
                Assert.True(
                   exceptionCaught != null && exceptionCaught is InvalidOperationException,
                   "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. Wrong exception was thrown: " + exceptionCaught.GetType().ToString());
            }
        }
コード例 #17
0
ファイル: ThreadLocalTests.cs プロジェクト: noahfalk/corefx
        private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres)
        {
            var tl = new ThreadLocal<object>(true);
            var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres));
            t.Wait();
            t = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value");
            Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type");
            tl.Dispose();

            object values;
            Assert.Throws<ObjectDisposedException>(() => values = tl.Values);
        }
コード例 #18
0
        public static void RunManualResetEventSlimTest5_Dispose_Negative()
        {
            ManualResetEventSlim mres = new ManualResetEventSlim(false);
            mres.Dispose();

            Assert.Throws<ObjectDisposedException>(() => mres.Reset());
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            Assert.Throws<ObjectDisposedException>(() => mres.Wait(0));
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            Assert.Throws<ObjectDisposedException>(
                () =>
                {
                    WaitHandle handle = mres.WaitHandle;
                });
            // Failure Case: The object has been disposed, should throw ObjectDisposedException.

            mres = new ManualResetEventSlim(false);

            ManualResetEvent mre = (ManualResetEvent)mres.WaitHandle;
            mres.Dispose();

            Assert.Throws<ObjectDisposedException>(() => mre.WaitOne(0));
            // Failure Case: The underlying event object has been disposed, should throw ObjectDisposedException.

        }
コード例 #19
0
ファイル: Scheduler.cs プロジェクト: koush/mono
		internal void ParticipateUntilInternal (Task self, ManualResetEventSlim evt, int millisecondsTimeout)
		{
			ThreadWorker.ParticipativeWorkerMethod (self, evt, millisecondsTimeout, workQueue, workers, pulseHandle);
		}
コード例 #20
0
ファイル: SynchronousQueue_Tests.cs プロジェクト: Baptista/PC
    private static bool TestSync()
    {
        const int RUN_TIME = 15000;
            const int SETUP_TIME = 20;
            const int CONSUM = 100;
            const int PRODUC = 100;
            const int QUEUE = 5;

            Thread[] consumthrs = new Thread[CONSUM];
            Thread[] producthrs = new Thread[PRODUC];

            int[] results = new int[PRODUC+1];
            int[] consumCounters = new int[CONSUM];
            int[] producCounters = new int[PRODUC];
            int[] interruptCounters = new int[CONSUM + PRODUC];
            int sentInterrupts = 0;

            ManualResetEventSlim startEvent = new ManualResetEventSlim(false);
            SynchronousQueue<int> sync = new SynchronousQueue<int>();

                for (int i = 0; i < PRODUC; i++)
                {
                    int tid = i;
                    producthrs[i] = new Thread(() =>
                    {

                        // Wait the start for all threads
                        startEvent.Wait();

                        int endTime = Environment.TickCount + RUN_TIME;
                        //do
                        //{
                            //do
                            //{
                                try
                                {
                                    sync.Put(tid+1 , tid+1);
                                    //break;
                                }
                                catch (ThreadInterruptedException)
                                {
                                    interruptCounters[tid]++;
                                }
                            //} while (true);
                            //Thread.Yield();
                        ++producCounters[tid];
                            //if ((++producCounters[tid] % 1000) == 0)
                            //{
                                Console.Write("[#p{0}]", tid);
                            //}
                        //} while (Environment.TickCount < endTime);
                        try
                        {
                            Thread.Sleep(0);
                        }
                        catch (ThreadInterruptedException)
                        {
                            interruptCounters[tid]++;
                        }
                    });
                    producthrs[i].Start();
                }

                for (int i = 0; i < CONSUM; i++)
                {
                    int tid = i;
                    consumthrs[i] = new Thread(() =>
                    {

                        // Wait the start for all threads
                        startEvent.Wait();

                        int endTime = Environment.TickCount + RUN_TIME;
                        //do
                        //{
                            //do
                            //{
                                try
                                {
                                    int result =  sync.Take(tid + 1);
                                    //if (result != 0)
                                    //{
                                        results[result] += 1;
                                    //}

                                    //break;
                                }
                                catch (ThreadInterruptedException)
                                {
                                    interruptCounters[tid + CONSUM]++;
                                }
                            //} while (true);
                            //Thread.Yield();
                        ++consumCounters[tid];
                            //if ((++consumCounters[tid] % 1000) == 0)
                            //{
                                Console.Write("[#c{0}]", tid);
                            //}
                        //} while (Environment.TickCount < endTime);
                        try
                        {
                            Thread.Sleep(0);
                        }
                        catch (ThreadInterruptedException)
                        {
                            interruptCounters[tid + CONSUM]++;
                        }
                    });
                    consumthrs[i].Start();
                }

                Thread.Sleep(SETUP_TIME);
                startEvent.Set();

                // Wait until all threads have been terminated.
                for (int i = 0; i < CONSUM + PRODUC; i++)
                {
                    if (i < CONSUM)
                        consumthrs[i].Join();
                    else
                        producthrs[i - CONSUM].Join();
                }

                // Show results
                Console.WriteLine("\nConsumers counters:");
                for (int i = 0; i < CONSUM; i++)
                {
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#c{0}: {1,4}]", i, consumCounters[i]);
                }

                Console.WriteLine("\nProducers counters:");
                for (int i = 0; i < PRODUC; i++)
                {
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#p{0}: {1,4}", i, producCounters[i]);
                }
                Console.WriteLine("\ninterrupt counters:");
                int sum = 0;
                for (int i = 0; i < CONSUM + PRODUC; i++)
                {
                    sum += interruptCounters[i];
                    if ((i % 5) == 0)
                        Console.WriteLine();
                    Console.Write("[#{0}: {1,4}]", i, interruptCounters[i]);
                }
                Console.WriteLine("\nsent interrupts: {0}, received: {1}", sentInterrupts, sum);

                for (int i = 1; i < results.Count(); i++)
                {
                    if (results[i] == 0)
                        return false;
                    Console.WriteLine(i);
                }

            return true;
    }
コード例 #21
0
 public CommandProcessorContext(Client client, ILogger log, ManualResetEventSlim doneEvent)
 {
     Client     = client;
     Log        = log;
     _doneEvent = doneEvent;
 }
コード例 #22
0
ファイル: TaskAwaiterTests.cs プロジェクト: ESgarbi/corefx
        public static void BaseSynchronizationContext_SameAsNoSynchronizationContext()
        {
            var quwi = new QUWITaskScheduler();
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                RunWithSchedulerAsCurrent(quwi, delegate
                {
                    ManualResetEventSlim mres = new ManualResetEventSlim();
                    var tcs = new TaskCompletionSource<object>();
                    var awaiter = ((Task)tcs.Task).GetAwaiter();

                    bool ranOnScheduler = false;
                    bool ranWithoutSyncCtx = false;
                    awaiter.OnCompleted(() =>
                    {
                        ranOnScheduler = (TaskScheduler.Current == quwi);
                        ranWithoutSyncCtx = SynchronizationContext.Current == null;
                        mres.Set();
                    });
                    Assert.False(mres.IsSet, "Callback should not yet have run.");

                    Task.Run(delegate { tcs.SetResult(null); });
                    mres.Wait();

                    Assert.True(ranOnScheduler, "Should have run on scheduler");
                    Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx");
                });
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
コード例 #23
0
 public static void RunManualResetEventSlimTest4_CombinedStateTests()
 {
     ManualResetEventSlim mres = new ManualResetEventSlim(false, 100);
     Assert.False(mres.IsSet,
        "RunManualResetEventSlimTest4_CombinedStateTests:  FAILED.  Set did not read correctly.");
     mres.Set();
     Assert.True(mres.IsSet,
        "RunManualResetEventSlimTest4_CombinedStateTests:  FAILED.  Set did not write/read correctly.");
 }
コード例 #24
0
        public static void RunManualResetEventSlimTest6_Exceptions()
        {
            ManualResetEventSlim mres = null;
            Assert.Throws<ArgumentOutOfRangeException>(() => mres = new ManualResetEventSlim(false, -1));
            // Failure Case: Constructor didn't throw AORE when -1 passed

            mres = new ManualResetEventSlim(false);

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(-2));
            // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.FromDays(-1)));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.MaxValue));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => mres.Wait(TimeSpan.MaxValue, new CancellationToken()));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max
        }
コード例 #25
0
        public async Task TestOrdering_Sync_OrderedDisabled()
        {
            // If ordering were enabled, this test would hang.

            var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, EnsureOrdered = false };

            var mres = new ManualResetEventSlim();
            var tb = new TransformBlock<int, int>(i =>
            {
                if (i == 0) mres.Wait();
                return i;
            }, options);
            tb.Post(0);
            tb.Post(1);

            Assert.Equal(1, await tb.ReceiveAsync());
            mres.Set();
            Assert.Equal(0, await tb.ReceiveAsync());

            tb.Complete();
            await tb.Completion;
        }
コード例 #26
0
ファイル: ParallelStateTest.cs プロジェクト: ESgarbi/corefx
        private int _iterCount = 0;  // test own counter for certain scenario, so the test can change behaviour after certain number of loop iteration

        #endregion

        #region Constructor

        public ParallelStateTest(TestParameters parameters)
        {
            _parameters = parameters;

            _mreSlim = new ManualResetEventSlim(false);

            _results = new double[parameters.Count];

            _sequences = new List<int>[1024];
            _sequences64 = new List<long>[1024];
            _threadCount = 0;

            // Set available actions
            _availableActions["Stop"] = StopAction;
            _availableActions["Break"] = BreakAction;
            _availableActions["Exceptional"] = ExceptionalAction;
            _availableActions["MultipleStop"] = MultipleStopAction;
            _availableActions["MultipleBreak"] = MultipleBreakAction;
            _availableActions["MultipleException"] = MultipleExceptionAction;
            _availableActions["SyncWaitStop"] = SyncWaitStop;
            _availableActions["SyncSetStop"] = SyncSetStop;
            _availableActions["SyncWaitBreak"] = SyncWaitBreak;
            _availableActions["SyncSetBreak"] = SyncSetBreak;

            _availableActions["SyncWaitStopCatchExp"] = SyncWaitStopCatchExp;
            _availableActions["SyncWaitBreakCatchExp"] = SyncWaitBreakCatchExp;

            _availableActions["SyncWaitExceptional"] = SyncWaitExceptional;
            _availableActions["SyncSetExceptional"] = SyncSetExceptional;

            // Set available verifications
            _availableVerifications["StopVerification"] = StopVerification;
            _availableVerifications["BreakVerification"] = BreakVerification;
            _availableVerifications["ExceptionalVerification"] = ExceptionalVerification;

            _barrier = new Barrier(parameters.Count);

            // A barrier is used in the workload to ensure that all tasks are running before any proceed.
            // This causes delays if the count is higher than the number of processors, as the thread pool
            // will need to (slowly) inject additional threads to meet the demand.  As a less-than-ideal
            // workaround, we change the thread pool's min thread count to be at least the number required
            // for the test.  Not perfect, but better than nothing.
            ThreadPoolHelpers.EnsureMinThreadsAtLeast(parameters.Count);

            int length = parameters.Count;
            if (length < 0)
                length = 0;

            if (parameters.Api != API.For)
            {
                int[] collArray = new int[length];
                for (int j = 0; j < length; j++)
                    collArray[j] = ((int)_startIndex) + j;

                if (parameters.Api == API.ForeachOnArray)
                    _collection = collArray;
                else if (parameters.Api == API.ForeachOnList)
                    _collection = new List<int>(collArray);
                else
                    _collection = collArray;
            }

            int index = 0;
            for (index = 0; index < parameters.Count; index++)
                _actions.Add(DummyAction);

            index = 0;
            foreach (string action in parameters.Actions)
            {
                Action<long, ParallelLoopState> a = null;
                string[] actionIndexPair = action.Split('_');

                if (!_availableActions.TryGetValue(actionIndexPair[0], out a))
                    throw new ArgumentException(actionIndexPair[0] + " is not a valid action");

                _actions[actionIndexPair.Length > 1 ? int.Parse(actionIndexPair[1]) : index++] = a;
            }

            foreach (string verification in parameters.Verifications)
            {
                Action<ParallelLoopResult?> act = null;

                if (!_availableVerifications.TryGetValue(verification, out act))
                    throw new ArgumentException(verification + " is not a valid verification");

                _verifications.Enqueue(act);
            }
        }
コード例 #27
0
        private int _iterCount = 0;  // test own counter for certain scenario, so the test can change behaviour after certain number of loop iteration

        #endregion

        #region Constructor

        public ParallelStateTest(TestParameters parameters)
        {
            _parameters = parameters;

            _mreSlim = new ManualResetEventSlim(false);

            _results = new double[parameters.Count];

            _sequences = new List<int>[1024];
            _sequences64 = new List<long>[1024];
            _threadCount = 0;

            // Set available actions
            _availableActions["Stop"] = StopAction;
            _availableActions["Break"] = BreakAction;
            _availableActions["Exceptional"] = ExceptionalAction;
            _availableActions["MultipleStop"] = MultipleStopAction;
            _availableActions["MultipleBreak"] = MultipleBreakAction;
            _availableActions["MultipleException"] = MultipleExceptionAction;
            _availableActions["SyncWaitStop"] = SyncWaitStop;
            _availableActions["SyncSetStop"] = SyncSetStop;
            _availableActions["SyncWaitBreak"] = SyncWaitBreak;
            _availableActions["SyncSetBreak"] = SyncSetBreak;

            _availableActions["SyncWaitStopCatchExp"] = SyncWaitStopCatchExp;
            _availableActions["SyncWaitBreakCatchExp"] = SyncWaitBreakCatchExp;

            _availableActions["SyncWaitExceptional"] = SyncWaitExceptional;
            _availableActions["SyncSetExceptional"] = SyncSetExceptional;

            // Set available verifications
            _availableVerifications["StopVerification"] = StopVerification;
            _availableVerifications["BreakVerification"] = BreakVerification;
            _availableVerifications["ExceptionalVerification"] = ExceptionalVerification;

            _barrier = new Barrier(parameters.Count);

            int length = parameters.Count;
            if (length < 0)
                length = 0;

            if (parameters.Api != API.For)
            {
                int[] collArray = new int[length];
                for (int j = 0; j < length; j++)
                    collArray[j] = ((int)_startIndex) + j;

                if (parameters.Api == API.ForeachOnArray)
                    _collection = collArray;
                else if (parameters.Api == API.ForeachOnList)
                    _collection = new List<int>(collArray);
                else
                    _collection = collArray;
            }

            int index = 0;
            for (index = 0; index < parameters.Count; index++)
                _actions.Add(DummyAction);

            index = 0;
            foreach (string action in parameters.Actions)
            {
                Action<long, ParallelLoopState> a = null;
                string[] actionIndexPair = action.Split('_');

                if (!_availableActions.TryGetValue(actionIndexPair[0], out a))
                    throw new ArgumentException(actionIndexPair[0] + " is not a valid action");

                _actions[actionIndexPair.Length > 1 ? int.Parse(actionIndexPair[1]) : index++] = a;
            }

            foreach (string verification in parameters.Verifications)
            {
                Action<ParallelLoopResult?> act = null;

                if (!_availableVerifications.TryGetValue(verification, out act))
                    throw new ArgumentException(verification + " is not a valid verification");

                _verifications.Enqueue(act);
            }
        }
コード例 #28
0
 public MyConnection(ManualResetEventSlim connectWh, ManualResetEventSlim disconnectWh)
 {
     _connectWh    = connectWh;
     _disconnectWh = disconnectWh;
 }
コード例 #29
0
ファイル: ThreadLocalTests.cs プロジェクト: noahfalk/corefx
        public static void RunThreadLocalTest5_Dispose()
        {
            // test recycling the combination index;
            ThreadLocal<string> tl = new ThreadLocal<string>(() => null);
            Assert.False(tl.IsValueCreated);
            Assert.Null(tl.Value);

            // Test that a value is not kept alive by a departed thread
            var threadLocal = new ThreadLocal<SetMreOnFinalize>();
            var mres = new ManualResetEventSlim(false);

            // (Careful when editing this test: saving the created thread into a local variable would likely break the 
            // test in Debug build.)
            // We are creating the task using TaskCreationOptions.LongRunning because...
            // there is no guarantee that the Task will be created on another thread.
            // There is also no guarantee that using this TaskCreationOption will force
            // it to be run on another thread.
            new Task(() => { threadLocal.Value = new SetMreOnFinalize(mres); }, TaskCreationOptions.LongRunning).Start(TaskScheduler.Default);

            SpinWait.SpinUntil(() =>
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                return mres.IsSet;
            }, 500);

            Assert.True(mres.IsSet);
        }
コード例 #30
0
        public static void WaitNotificationTest()
        {
            ThreadTestHelpers.RunTestInBackgroundThread(() =>
            {
                var tsc = new TestSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(tsc);
                Assert.Same(tsc, SynchronizationContext.Current);

                var e = new ManualResetEvent(false);
                tsc.WaitAction = () => e.Set();
                Assert.False(tsc.IsWaitNotificationRequired());
                Assert.False(e.WaitOne(0));
                tsc.SetWaitNotificationRequired();
                Assert.True(tsc.IsWaitNotificationRequired());
                Assert.True(e.WaitOne(0));

                var mres = new ManualResetEventSlim();
                tsc.WaitAction = () => mres.Set();
                mres.Reset();
                mres.CheckedWait();

                e.Reset();
                tsc.WaitAction = () => e.Set();
                SynchronizationContext.SetSynchronizationContext(new TestSynchronizationContext());
                Assert.False(e.WaitOne(0));
                SynchronizationContext.SetSynchronizationContext(tsc);
                Assert.True(e.WaitOne(0));
                e.Reset();
                e.CheckedWait();

                e.Reset();
                var lockObj = new object();
                var lockAcquiredFromBackground = new AutoResetEvent(false);
                Action waitForThread;
                Thread t =
                    ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                    {
                        lock (lockObj)
                        {
                            lockAcquiredFromBackground.Set();
                            e.CheckedWait();
                        }
                    });
                t.IsBackground = true;
                t.Start();
                lockAcquiredFromBackground.CheckedWait();
                Assert.True(Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
                Monitor.Exit(lockObj);
                waitForThread();

                e.Reset();
                var m = new Mutex();
                t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                {
                    m.CheckedWait();
                    try
                    {
                        lockAcquiredFromBackground.Set();
                        e.CheckedWait();
                    }
                    finally
                    {
                        m.ReleaseMutex();
                    }
                });
                t.IsBackground = true;
                t.Start();
                lockAcquiredFromBackground.CheckedWait();
                m.CheckedWait();
                m.ReleaseMutex();
                waitForThread();
            });
        }
コード例 #31
0
 public static void RunManualResetEventSlimTest5_Dispose()
 {
     ManualResetEventSlim mres = new ManualResetEventSlim(false);
     try
     {
         mres.Dispose();
     }
     catch
     {
         Assert.True(false, string.Format("RunManualResetEventSlimTest5_Dispose: FAILED.  Calling Dispose on a disposed MRES shouldn't throw"));
     }
 }
コード例 #32
0
ファイル: TaskAwaiterTests.cs プロジェクト: ESgarbi/corefx
        public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await

                var quwi = new QUWITaskScheduler();
                RunWithSchedulerAsCurrent(quwi, delegate
                {
                    Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");

                    // Create the not completed task and get its awaiter
                    var mres = new ManualResetEventSlim();
                    var tcs = new TaskCompletionSource<object>();

                    // Hook up the callback
                    bool ranOnScheduler = false;
                    Action callback = () =>
                    {
                        ranOnScheduler = (TaskScheduler.Current == quwi);
                        mres.Set();
                    };
                    if (generic)
                    {
                        if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        else tcs.Task.GetAwaiter().OnCompleted(callback);
                    }
                    else
                    {
                        if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                    }
                    Assert.False(mres.IsSet, "Callback should not yet have run.");

                    // Complete the task in another scheduler and wait for the callback to run
                    Task.Run(delegate { tcs.SetResult(null); });
                    mres.Wait();

                    // Validate the callback ran on the right scheduler
                    bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                    Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
                });
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
コード例 #33
0
 // We use this intermediary method to improve chances of GC kicking
 static void CreateAndForgetFaultedTask(ManualResetEventSlim evt)
 {
     Task.Factory.StartNew(() => { evt.Set(); throw new Exception("foo"); });
 }