Example #1
0
        public void RunApplicationTest()
        {
            var parameters = new[] { "a", "b", "longParam with spaces and ` \x305 other chars" };
            var manager    = SingleInstanceManager.CreateManager("unitTest");

            var start1 = manager.RunApplication(new string[] { });

            Assert.AreEqual(true, start1);

            var m = new Barrier(2);

            manager.SecondInstanceStarted += (sender, e) =>
            {
                CollectionAssert.AreEqual(parameters, e.CommandLineParameters);
                m.SignalAndWait();
                m.Dispose();
            };

            var t = new Thread(() =>
            {
                var start2 = manager.RunApplication(parameters);
                Assert.AreEqual(false, start2);
            });


            t.Start();
            t.Join();

            if (!m.SignalAndWait(10000))
            {
                Assert.Warn("Signal timed out");
            }
            ;
            manager.Shutdown();
        }
Example #2
0
        /// <summary cref="DisposeBase.Dispose(bool)"/>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            lock (taskSynchronizationObject)
            {
                running     = false;
                currentTask = null;
                Monitor.PulseAll(taskSynchronizationObject);
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }
            threads = null;
            foreach (var warp in warpContexts)
            {
                warp.Dispose();
            }
            warpContexts = null;
            foreach (var group in groupContexts)
            {
                group.Dispose();
            }
            groupContexts = null;
            finishedEvent.Dispose();
        }
        [Fact(Skip = "Barrier doesn't block the async sends in core.")] // TODO: make this test work
        public async Task NotifyCallQueueOnEveryUserButPostingUser()
        {
            var service = GetService();
            var topic   = new Topic {
                TopicID = 123
            };
            var user = new User {
                UserID = 768
            };
            var list = new List <User> {
                user, new User {
                    UserID = 2
                }
            };

            _mockSubRepo.Setup(s => s.GetSubscribedUsersThatHaveViewed(topic.TopicID)).ReturnsAsync(list);
            var topicLink = "foo";
            Func <User, Topic, string> gen = (u, t) => "x" + u.UserID;
            var barrier = new Barrier(1);

            async Task ActionAsync()
            {
                await service.NotifySubscribers(topic, user, topicLink, gen);

                barrier.SignalAndWait();
            }

            await ActionAsync();

            barrier.Dispose();
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, It.IsAny <User>(), topicLink, It.IsAny <string>()), Times.Exactly(1));
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[0], topicLink, "x" + list[0].UserID), Times.Exactly(0));
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[1], topicLink, "x" + list[1].UserID), Times.Exactly(1));
        }
        public void NotifyCallQueueOnEveryUserButPostingUser()
        {
            var service = GetService();
            var topic   = new Topic(123);
            var user    = new User(768, DateTime.MinValue);
            var list    = new List <User> {
                user, new User(2, DateTime.MinValue)
            };

            _mockSubRepo.Setup(s => s.GetSubscribedUsersThatHaveViewed(topic.TopicID)).Returns(list);
            var topicLink           = "foo";
            Func <User, string> gen = u => "x" + u.UserID;
            var    barrier          = new Barrier(1);
            Action action           = () =>
            {
                service.NotifySubscribers(topic, user, topicLink, gen);
                barrier.SignalAndWait();
            };

            action.Invoke();
            barrier.Dispose();
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, It.IsAny <User>(), topicLink, It.IsAny <string>()), Times.Exactly(1));
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[0], topicLink, "x" + list[0].UserID), Times.Exactly(0));
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[1], topicLink, "x" + list[1].UserID), Times.Exactly(1));
        }
        [Fact(Skip = "Barrier doesn't block the async sends in core.")]         // TODO: make this test work
        public void NotifyCallQueueOnEveryUser()
        {
            var service = GetService();
            var topic   = new Topic {
                TopicID = 123
            };
            var list = new List <User> {
                new User {
                    UserID = 1
                }, new User {
                    UserID = 2
                }
            };

            _mockSubRepo.Setup(s => s.GetSubscribedUsersThatHaveViewed(topic.TopicID)).Returns(list);
            var topicLink           = "foo";
            Func <User, string> gen = u => "x" + u.UserID;
            var    barrier          = new Barrier(1);
            Action action           = () => {
                service.NotifySubscribers(topic, new User {
                    UserID = 45643
                }, topicLink, gen);
                barrier.SignalAndWait();
            };

            action();
            barrier.Dispose();
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[0], topicLink, "x" + list[0].UserID), Times.Once());
            _mockSubTopicEmail.Verify(s => s.ComposeAndQueue(topic, list[1], topicLink, "x" + list[1].UserID), Times.Once());
        }
Example #6
0
        /// <summary>
        /// Dispose all managed resources allocated by this CPU accelerator instance.
        /// </summary>
        protected override void DisposeAccelerator_SyncRoot(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            // Dispose task engine
            lock (taskSynchronizationObject)
            {
                running     = false;
                currentTask = null;
                Monitor.PulseAll(taskSynchronizationObject);
            }

            // Dispose all multiprocessors
            foreach (var multiprocessor in multiprocessors)
            {
                multiprocessor.Dispose();
            }

            // Dispose barriers
            finishedEventPerMultiprocessor.Dispose();
            taskConcurrencyLimit.Dispose();
        }
Example #7
0
        public static void RunBarrierTest6_Dispose()
        {
            Barrier b = new Barrier(1);

            b.Dispose();
            Assert.Throws <ObjectDisposedException>(() => b.SignalAndWait());
        }
Example #8
0
        /// <summary>
        /// Download all the images for the current session
        /// </summary>
        public void DownloadAllTreatmentImages()
        {
            Barrier barrier = new Barrier(_patient.PatientTreatment.TrainingList.Count + 2);

            Task treatmentThread = new Task(() =>
            {
                //Downloading all thumbs in treatment
                DownloadTreatment();

                barrier.SignalAndWait();
            });

            treatmentThread.Start();

            foreach (Training t in _patient.PatientTreatment.TrainingList)
            {
                Task tt = new Task(() =>
                {
                    DownloadTraining(_patient.PatientTreatment.TrainingList.IndexOf(t));
                    barrier.SignalAndWait();
                });
                tt.Start();
            }

            barrier.SignalAndWait();
            barrier.Dispose();
        }
Example #9
0
        public static void RunBarrierTest10c()
        {
            for (int j = 0; j < 10000; j++)
            {
                Task[]  tasks = new Task[2];
                Barrier b     = new Barrier(3);
                tasks[0] = Task.Run(() => b.SignalAndWait());
                tasks[1] = Task.Run(() => b.SignalAndWait());


                b.SignalAndWait();
                b.Dispose();

                GC.Collect();

                try
                {
                    Task.WaitAll(tasks);
                }
                catch
                {
                    Assert.True(false, string.Format("RunBarrierTest10c:  Error: Only finished {0} iterations, before an exception was thrown.", j));
                }
            }
        }
        /// <summary>
        /// Depending on data destination calls appropriate functions to start measurement.
        /// </summary>
        /// <param name="tasks">A list of Tasks</param>
        static void GoToRecorderRecordingState()
        {
            var threads = new Thread[numOfModules];

            barrier = new Barrier(numOfModules);
            try
            {
                for (int i = 0; i < numOfModules; i++)
                {
                    threads[i] = new Thread((object idx) =>
                    {
                        if (destIsSDcard)
                        {
                            StartSDcarMeasuremnet((int)idx);
                        }
                        else
                        {
                            StartSocketMeasuremnet((int)idx);
                        }
                    });
                    threads[i].Start(i);
                }
                for (int i = 0; i < numOfModules; i++)
                {
                    threads[i].Join();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("GoToRecorderRecordingState(exception): {0}", ex.Message);
            }
            barrier.Dispose();
        }
Example #11
0
        // Demonstrates:
        //      Barrier constructor with post-phase action
        //      Barrier.AddParticipants()
        //      Barrier.RemoveParticipant()
        //      Barrier.SignalAndWait(), incl. a BarrierPostPhaseException being thrown
        static void Main(string[] args)
        {
            int count = 0;

            // Create a barrier with three participants
            // Provide a post-phase action that will print out certain information
            // And the third time through, it will throw an exception
            Barrier barrier = new Barrier(3, (b) =>
            {
                Console.WriteLine("Post-Phase action: count={0}, phase={1}", count, b.CurrentPhaseNumber);
                if (b.CurrentPhaseNumber == 2) /*throw new Exception("D'oh!");*/
                {
                    Console.WriteLine("Currently the Phase number is 2");
                }
            });

            // Nope -- changed my mind.  Let's make it five participants.
            barrier.AddParticipants(2);

            // Nope -- let's settle on four participants.
            barrier.RemoveParticipant();


            // This is the logic run by all participants
            Action action = () =>
            {
                Interlocked.Increment(ref count);
                barrier.SignalAndWait(); // during the post-phase action, count should be 4 and phase should be 0
                Interlocked.Increment(ref count);
                barrier.SignalAndWait(); // during the post-phase action, count should be 8 and phase should be 1

                // The third time, SignalAndWait() will throw an exception and all participants will see it
                Interlocked.Increment(ref count);
                try
                {
                    barrier.SignalAndWait();
                }
                catch (Exception bppe)
                {
                    Console.WriteLine("Caught BarrierPostPhaseException: {0}", bppe.Message);
                }

                // The fourth time should be hunky-dory
                Interlocked.Increment(ref count);
                barrier.SignalAndWait(); // during the post-phase action, count should be 16 and phase should be 3
            };

            // Now launch 4 parallel actions to serve as 4 participants
            Parallel.Invoke(action, action, action, action);

            // This (5 participants) would cause an exception:
            // Parallel.Invoke(action, action, action, action, action);
            //      "System.InvalidOperationException: The number of threads using the barrier
            //      exceeded the total number of registered participants."

            // It's good form to Dispose() a barrier when you're done with it.
            barrier.Dispose();

            Console.ReadKey();
        }
Example #12
0
 public void Dispose()
 {
     if (barrier != null)
     {
         barrier.Dispose();
         barrier = null;
     }
 }
Example #13
0
        public static void Run()
        {
            _tasks   = new Task[_particapants];
            _barrier = new Barrier(_particapants, (barrier) =>
            {
                Console.WriteLine("Current phase: {0}", barrier.CurrentPhaseNumber);
            });
            var sl           = new SpinLock(false);
            int totalRenders = 0;

            for (int i = 0; i < _particapants; i++)
            {
                _tasks[i] = Task.Factory.StartNew((num) =>
                {
                    var localsb           = new StringBuilder();
                    var paiticipantNumber = (int)num;
                    for (int j = 0; j < 10; j++)
                    {
                        CreatePlanets(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CreateStars(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionBetweenPlanets(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionBetweenStars(paiticipantNumber);
                        _barrier.SignalAndWait();
                        RenderCollisions(paiticipantNumber);
                        _barrier.SignalAndWait();

                        bool lockTaken = false;
                        try
                        {
                            sl.Enter(ref lockTaken);
                            // Spinlock acquired a lock
                            // Critical section
                            totalRenders++;
                        }
                        finally
                        {
                            if (lockTaken)
                            {
                                sl.Exit(false);
                            }
                        }
                    }
                }, i);
            }
            //很多任务完成其工作之后
            var finalTask = Task.Factory.ContinueWhenAll(_tasks, (tasks) =>
            {
                Task.WaitAll(_tasks);
                Console.WriteLine("{0} renders were executed.", totalRenders);
                _barrier.Dispose();
            });

            finalTask.Wait();
            Console.ReadLine();
        }
Example #14
0
 /// <summary cref="DisposeBase.Dispose(bool)"/>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         barrier.Dispose();
         broadcastBuffer.Dispose();
     }
     base.Dispose(disposing);
 }
Example #15
0
 /// <summary cref="DisposeBase.Dispose(bool)"/>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         groupBarrier.Dispose();
         sharedMemoryBuffer.Dispose();
         broadcastBuffer.Dispose();
     }
     base.Dispose(disposing);
 }
Example #16
0
 private void EndWork()
 {
     Working = false;
     if (_barrierForReps != null)
     {
         _barrierForReps.Dispose();
         _barrierForReps = null;
     }
     _asyncOperation = null;
 }
Example #17
0
        public void Dispose()
        {
            if (!_waited)
            {
                throw new ApplicationException("Please wait on barrier");
            }

            _barrier?.Dispose();
            _barrier = null;
        }
Example #18
0
        static void Main()
        {
            Console.WriteLine("人到齐了才能开会");

            new Thread(Arrival1).Start();
            new Thread(Arrival2).Start();
            new Thread(Arrival3).Start();

            Console.ReadKey();
            b.Dispose();
        }
        public Task SwitchBuffer()
        {
            // Make sure that the agent is able to switch to the secondary buffer when the primary is full/busy
            var api   = new Mock <IApi>();
            var agent = new AgentWriter(api.Object, statsd: null);

            var barrier = new Barrier(2);

            api.Setup(a => a.SendTracesAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <int>()))
            .Callback(() =>
            {
                barrier.SignalAndWait();
                barrier.SignalAndWait();
            })
            .Returns(Task.FromResult(true));

            agent.WriteTrace(CreateTrace(1));

            // Wait for the flush operation
            barrier.SignalAndWait();

            // At this point, the flush thread is stuck in Api.SendTracesAsync, and the frontBuffer should be active and locked
            Assert.True(agent.ActiveBuffer == agent.FrontBuffer);
            Assert.True(agent.FrontBuffer.IsLocked);
            Assert.Equal(1, agent.FrontBuffer.TraceCount);
            Assert.Equal(1, agent.FrontBuffer.SpanCount);

            var mutex = new ManualResetEventSlim();

            agent.WriteTrace(CreateTrace(2));

            // Wait for the trace to be dequeued
            WaitForDequeue(agent);

            // Since the frontBuffer was locked, the buffers should have been swapped
            Assert.True(agent.ActiveBuffer == agent.BackBuffer);
            Assert.Equal(1, agent.BackBuffer.TraceCount);
            Assert.Equal(2, agent.BackBuffer.SpanCount);

            // Unblock the flush thread
            barrier.SignalAndWait();

            // Wait for the next flush operation
            barrier.SignalAndWait();

            // Back buffer should still be active and being flushed
            Assert.True(agent.ActiveBuffer == agent.BackBuffer);
            Assert.True(agent.BackBuffer.IsLocked);
            Assert.False(agent.FrontBuffer.IsLocked);

            // Unblock and exit
            barrier.Dispose();
            return(agent.FlushAndCloseAsync());
        }
Example #20
0
 /// <inheritdoc/>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         barrier.Dispose();
         foreach (var warpBarrier in warpBarriers)
         {
             warpBarrier.Dispose();
         }
     }
     base.Dispose(disposing);
 }
Example #21
0
        static void Main(string[] args)
        {
            _tasks   = new Task[_participants];
            _barrier = new Barrier(_participants, (barrier) =>
            {
                Console.WriteLine("Current phase: {0}",
                                  barrier.CurrentPhaseNumber);
            });

            int totalRenders = 0;

            for (int i = 0; i < _participants; i++)
            {
                _tasks[i] = Task.Factory.StartNew((num) =>
                {
                    var participantNumber = (int)num;
                    for (int j = 0; j < 10; j++)
                    {
                        CreatePlanets(participantNumber);
                        _barrier.SignalAndWait();
                        CreateStars(participantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionsBetweenPlanets(participantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionsBetweenStars(participantNumber);
                        _barrier.SignalAndWait();
                        RenderCollisions(participantNumber);
                        _barrier.SignalAndWait();

                        // Increment totalRenders with an atomic operation
                        Interlocked.Increment(ref totalRenders);
                    }
                }, i);
            }

            var finalTask = Task.Factory.ContinueWhenAll(_tasks, (tasks) =>
            {
                // Wait for all the tasks to ensure
                // the propagation of any exception occurred
                // in any of the _tasks
                Task.WaitAll(_tasks);
                Console.WriteLine(
                    "{0} renders were executed.",
                    totalRenders);
                // Dispose the Barrier instance
                _barrier.Dispose();
            });

            // Wait for finalTask to finish
            finalTask.Wait();

            Console.ReadLine();
        }
Example #22
0
        public static async Task Run()
        {
            Barrier barrier = new Barrier(3, b =>
            {
                Console.WriteLine("Barrier method: phase={0}", b.CurrentPhaseNumber);

                if (b.CurrentPhaseNumber == 2)
                {
                    Console.WriteLine();
                    Console.WriteLine($"### Finished.");
                    Console.WriteLine();
                }

                Console.WriteLine();
            });

            void Action()
            {
                Console.WriteLine($"Before Phase 1 Tid: {Thread.CurrentThread.ManagedThreadId}");
                if (Thread.CurrentThread.ManagedThreadId == 1)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(3));
                }

                barrier.SignalAndWait(); // during the post-phase action, count should be 4 and phase should be 0
                Console.WriteLine($"After Phase 1 Tid: {Thread.CurrentThread.ManagedThreadId}");

                Console.WriteLine($"Before Phase 2 Tid: {Thread.CurrentThread.ManagedThreadId}");
                if (Thread.CurrentThread.ManagedThreadId == 1)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(3));
                }

                barrier.SignalAndWait(); // during the post-phase action, count should be 8 and phase should be 1
                Console.WriteLine($"After Phase 2 Tid: {Thread.CurrentThread.ManagedThreadId}");

                Console.WriteLine($"Before Phase 3 Tid: {Thread.CurrentThread.ManagedThreadId}");
                if (Thread.CurrentThread.ManagedThreadId == 1)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(3));
                }

                barrier.SignalAndWait(); // during the post-phase action, count should be 8 and phase should be 1

                Console.WriteLine($"After Phase 3 Tid: {Thread.CurrentThread.ManagedThreadId}");
            }

            Parallel.Invoke(Action, Action, Action);

            // It's good form to Dispose() a barrier when you're done with it.
            barrier.Dispose();
        }
Example #23
0
        public static void TestThrowException()
        {
            Console.WriteLine("BarrierTest.TestThrowException   Begin");
            _tasks   = new Task[_participants];
            _barrier = new Barrier(_participants, barrier =>
            {
                Console.WriteLine($"Current phase: {barrier.CurrentPhaseNumber}");
                if (barrier.CurrentPhaseNumber == 10)
                {
                    throw new InvalidOperationException("No more phases allowed");
                }
            });

            for (int i = 0; i < _participants; i++)
            {
                _tasks[i] = Task.Factory.StartNew(num =>
                {
                    var participantNumber = (int)num;
                    for (int j = 0; j < 10; j++)
                    {
                        CreatePlanets(participantNumber);
                        try
                        {
                            _barrier.SignalAndWait();
                        }
                        catch (BarrierPostPhaseException bppex)
                        {
                            Console.WriteLine(bppex.InnerException.Message);
                            break;
                        }
                        CreateStars(participantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionsBetweenPlanets(participantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionsBetweenStars(participantNumber);
                        _barrier.SignalAndWait();
                        RenderCollisions(participantNumber);
                        _barrier.SignalAndWait();
                    }
                }, i);
            }

            var finalTask = Task.Factory.ContinueWhenAll(_tasks, tasks =>
            {
                Task.WaitAll(_tasks);
                Console.WriteLine("All the phases were executed.");
                _barrier.Dispose();
            });

            finalTask.Wait();
        }
Example #24
0
        public void BarrierExceptionTest()
        {
            var barrier = new Barrier(3, barrier1 =>
            {
                if (barrier1.CurrentPhaseNumber == 2)
                {
                    throw new Exception("phase number 2.");
                }
            });

            var tasks = new Task[3];

            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(100);
                    Trace.WriteLine($"{Thread.CurrentThread.ManagedThreadId} operation 1.");
                    barrier.SignalAndWait();

                    Thread.Sleep(100);
                    Trace.WriteLine($"{Thread.CurrentThread.ManagedThreadId} operation 2.");
                    barrier.SignalAndWait();

                    Thread.Sleep(100);
                    Trace.WriteLine($"{Thread.CurrentThread.ManagedThreadId} operation 3.");
                    try
                    {
                        barrier.SignalAndWait();
                    }
                    catch (BarrierPostPhaseException ex)
                    {
                        Trace.WriteLine(ex.Message);
                        Trace.WriteLine(ex.InnerException.Message);
                    }
                });
            }

            try
            {
                Task.WaitAll(tasks);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                barrier.Dispose();
            }
        }
        public void Dispose()
        {
            _isDisposed = true;
            _mre.Set();
            _mre.Close();
            _countEvt.Dispose();

            _barrier.SignalAndWait();
            CheckAllThreadsFinished();
            _barrier.Dispose();

            _mre       = null;
            _workItems = null;
        }
Example #26
0
        public static void RunBarrierTest6_Dispose()
        {
            Barrier b = new Barrier(1);

            b.Dispose();
            try
            {
                b.SignalAndWait();
                Assert.True(false, string.Format("BarrierTests:  Cancel failed, SignalAndWait didn't throw exceptions after Dispose."));
            }
            catch (ObjectDisposedException)
            {
            }
        }
Example #27
0
 public void Run()
 {
     ThrowIfDisposed();
     if (_isRunning)
     {
         return;
     }
     _isRunning = true;
     _barrier?.Dispose();
     _barrier = new Barrier(this.QueueOptions.ConsumeConcurrencyLevel);
     foreach (var i in Enumerable.Range(1, this.QueueOptions.ConsumeConcurrencyLevel))
     {
         this.StartParallel();
     }
 }
Example #28
0
        public static void RunBarrierTest10c()
        {
            for (int j = 0; j < 10; j++)
            {
                Task[]  tasks = new Task[2];
                Barrier b     = new Barrier(3);
                tasks[0] = Task.Run(() => b.SignalAndWait());
                tasks[1] = Task.Run(() => b.SignalAndWait());

                b.SignalAndWait();
                b.Dispose();

                GC.Collect();

                Task.WaitAll(tasks);
            }
        }
 public void Dispose()
 {
     if (this.m_partitionIndex == 0)
     {
         for (int i = 0; i < this.m_sharedBarriers.GetLength(0); i++)
         {
             for (int j = 0; j < this.m_sharedBarriers.GetLength(1); j++)
             {
                 Barrier barrier = this.m_sharedBarriers[i, j];
                 if (barrier != null)
                 {
                     barrier.Dispose();
                 }
             }
         }
     }
 }
        public static void Run()
        {
            var cts = new System.Threading.CancellationTokenSource();
            var ct  = cts.Token;

            _tasks   = new Task[_particapants];
            _barrier = new Barrier(_particapants, (barrier) =>
            {
                Console.WriteLine("Current phase: {0}", barrier.CurrentPhaseNumber);
            });
            var s1           = new SpinLock(false);
            int totalRenders = 0;

            for (int i = 0; i < _particapants; i++)
            {
                _tasks[i] = Task.Factory.StartNew((num) =>
                {
                    var paiticipantNumber = (int)num;
                    for (int j = 0; j < 10; j++)
                    {
                        CreatePlanets(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CreateStars(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionBetweenPlanets(paiticipantNumber);
                        _barrier.SignalAndWait();
                        CheckCollisionBetweenStars(paiticipantNumber);
                        _barrier.SignalAndWait();
                        RenderCollisions(paiticipantNumber);
                        _barrier.SignalAndWait();
                        Interlocked.Increment(ref totalRenders);
                    }
                }, i, ct);
            }
            //很多任务完成其工作之后
            var finalTask = Task.Factory.ContinueWhenAll(_tasks, (tasks) =>
            {
                Task.WaitAll(_tasks);
                Console.WriteLine("{0} renders were executed.", totalRenders);
                _barrier.Dispose();
            });

            finalTask.Wait();
            Console.ReadLine();
        }
        public static void BarrierCancellationTestsCancelBeforeWait()
        {
            Barrier barrier = new Barrier(3);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

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

            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(millisec, ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(
               () => barrier.SignalAndWait(timeSpan, ct), ct,
               "CancelBeforeWait:  An OCE should have been thrown.");

            barrier.Dispose();
        }
Example #32
0
 public static void RunBarrierTest6_Dispose()
 {
     Barrier b = new Barrier(1);
     b.Dispose();
     try
     {
         b.SignalAndWait();
         Assert.True(false, string.Format("BarrierTests:  Cancel failed, SignalAndWait didn't throw exceptions after Dispose."));
     }
     catch (ObjectDisposedException)
     {
     }
 }
Example #33
0
        public static void RunBarrierTest10c()
        {
            for (int j = 0; j < 10000; j++)
            {
                Task[] tasks = new Task[2];
                Barrier b = new Barrier(3);
                tasks[0] = Task.Run(() => b.SignalAndWait());
                tasks[1] = Task.Run(() => b.SignalAndWait());


                b.SignalAndWait();
                b.Dispose();

                GC.Collect();

                try
                {
                    Task.WaitAll(tasks);
                }
                catch
                {
                    Assert.True(false, string.Format("RunBarrierTest10c:  Error: Only finished {0} iterations, before an exception was thrown.", j));
                }
            }
        }
Example #34
0
 public static void RunBarrierTest6_Dispose()
 {
     Barrier b = new Barrier(1);
     b.Dispose();
     Assert.Throws<ObjectDisposedException>(() => b.SignalAndWait());
 }
Example #35
0
        public static void RunBarrierTest10c()
        {
            for (int j = 0; j < 10000; j++)
            {
                Task[] tasks = new Task[2];
                Barrier b = new Barrier(3);
                tasks[0] = Task.Run(() => b.SignalAndWait());
                tasks[1] = Task.Run(() => b.SignalAndWait());

                b.SignalAndWait();
                b.Dispose();

                GC.Collect();

                Task.WaitAll(tasks);
            }
        }