public void DoWorkShouldNotCallWorkItemDequeueWhenWorkerThreadManagerShouldExitWorkerThreadReturnsTrue()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue    = Substitute.For <IWorkItemQueue>();
            WorkerThread     workerThread     = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.WorkerThreadExiting += (sender, args) =>
            {
                if (args.WorkerThreadExitReason == WorkerThreadExitReason.MaximumThreadCountExceeded)
                {
                    manualResetEvent.Set();
                }
            };
            workerThreadManager.ShouldExitWorkerThread(workerThread, false).ReturnsForAnyArgs(true);
            workerThread.Start();

            manualResetEvent.WaitOne(500);

            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            workItemQueue.DidNotReceive().Dequeue();
        }
        public void DoWorkShouldExitWorkerThreadWhenWorkerThreadManagerShouldExitWorkerThreadReturnsTrueAndWorkItemQueueIsEmpty()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue    = Substitute.For <IWorkItemQueue>();

            workItemQueue.Dequeue().Returns((IWorkItem)null);

            bool         exitedBecaseWorkItemQueueIsEmpty = false;
            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.WorkerThreadExiting += (sender, args) =>
            {
                if (args.WorkerThreadExitReason == WorkerThreadExitReason.WorkItemQueueIsEmpty)
                {
                    exitedBecaseWorkItemQueueIsEmpty = true;
                    manualResetEvent.Set();
                }
            };
            workerThreadManager.ShouldExitWorkerThread(workerThread, false).Returns(false);
            workerThreadManager.ShouldExitWorkerThread(workerThread, true).Returns(true);

            workerThread.Start();

            manualResetEvent.WaitOne(500);
            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            workItemQueue.Received(1).Dequeue();
            Assert.AreEqual(true, exitedBecaseWorkItemQueueIsEmpty);
        }
        public void StopShouldCallCurrentWorkItemStopMethodWhenCalledDuringAnyWorkItemIsInProgress()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent startWaitHandle = new ManualResetEvent(false);
            ManualResetEvent stopWaitHandle  = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue   = Substitute.For <IWorkItemQueue>();
            IWorkItem        workItem        = Substitute.For <IWorkItem>();

            workItem.When(x => x.DoWork()).Do(
                x =>
            {
                startWaitHandle.Set();
                stopWaitHandle.WaitOne(500);
            });
            workItemQueue.Dequeue().Returns(workItem);

            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThread.Start();

            startWaitHandle.WaitOne(500);
            workerThread.Stop();
            stopWaitHandle.Set();

            Wait.While(() => workerThread.Thread.IsAlive, 500);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            workItem.Received(1).Stop();
        }
Esempio n. 4
0
 public MailerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IWorkItemQueue workItemQueue, IEmailClient emailClient)
 {
     _next          = next;
     _logger        = loggerFactory.CreateLogger <MailerMiddleware>();
     _workItemQueue = workItemQueue;
     _emailClient   = emailClient;
 }
        /// <summary>
        /// Adds the request to build a texture for the specified planet onto a build queue
        /// </summary>
        public void QueueBuild( IWorkItemQueue queue, ISpherePlanet planet, Action<ITexture> onComplete )
        {
            SourceSinkWorkItem.Builder<Bitmap[]> sourceSink = new SourceSinkWorkItem.Builder<Bitmap[]>( );
            sourceSink.SetSource( CreateTextureBitmaps, planet );
            sourceSink.SetSink( FinishBuild, onComplete );

            queue.Enqueue( sourceSink.Build( "Build Marble Texture" ), null );
        }
        public void DoWorkShouldCallWorkerThreadWorkItemExceptionEventWhenWorkItemIsCompletedWithException()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            Exception        invalidCastException = new InvalidCastException();
            ManualResetEvent manualResetEvent     = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue        = Substitute.For <IWorkItemQueue>();
            IWorkItem        workItem             = Substitute.For <IWorkItem>();

            workItem.When(x => x.DoWork()).Do(
                x =>
            {
                throw invalidCastException;
            });
            workItemQueue.Dequeue().Returns(workItem);

            Exception    otherThreadsException = null;
            bool         workerThreadWorkItemExceptionEventIsCalled = false;
            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.WorkerThreadWorkItemException += (sender, args) =>
            {
                workerThreadWorkItemExceptionEventIsCalled = true;

                try
                {
                    Assert.AreEqual(WorkItemState.CompletedWithException, workItem.State);
                    Assert.AreEqual(workItem, args.WorkItem);
                    Assert.AreEqual(workItem.LastException, args.Exception);
                    Assert.AreEqual(invalidCastException, args.Exception);
                    workItem.Received(1).DoWork();
                }
                catch (Exception ex)
                {
                    otherThreadsException = ex;
                }

                workerThread.Stop();
                manualResetEvent.Set();
            };
            workerThread.Start();

            manualResetEvent.WaitOne(500);
            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            Assert.AreEqual(true, workerThreadWorkItemExceptionEventIsCalled);

            if (otherThreadsException != null)
            {
                throw otherThreadsException;
            }
        }
        public void ConstructorTestInitialWorkerThreadsCount(int workItemQueueCount, int minWorkerThreads, int maxWorkerThreads, int expected)
        {
            IWorkItemQueue workItemQueue = Substitute.For <IWorkItemQueue>();

            workItemQueue.Count.Returns(workItemQueueCount);
            WorkerThreadPool workerThreadPool = new WorkerThreadPool(workItemQueue, minWorkerThreads, maxWorkerThreads);

            Assert.AreEqual(expected, workerThreadPool.WorkerThreadsCount);

            workerThreadPool.Shutdown(true, 500);
        }
        public void ConstructorShouldCreateOptimumWorkerThreadsWhenThereAreWorkItemsInTheQueue(int workItemCount, int expected)
        {
            IWorkItemQueue workItemQueue = Substitute.For <IWorkItemQueue>();

            workItemQueue.Count.Returns(workItemCount);

            WorkerThreadPool workerThreadPool = new WorkerThreadPool(workItemQueue, 2, 4);

            Assert.AreEqual(expected, workerThreadPool.WorkerThreadsCount);

            workerThreadPool.Shutdown(true, 500);
        }
        /// <summary>
        /// Setup constructor
        /// </summary>
        /// <param name="uiProvider">UI provider. If null, no error messages are shown to the user</param>
        /// <param name="view">View to control</param>
        /// <param name="model">Animation model</param>
        /// <param name="workQueue">Work queue</param>
        public WaveAnimatorController( IMessageUiProvider uiProvider, IWaveAnimatorView view, WaveAnimationParameters model, IWorkItemQueue workQueue )
        {
            Arguments.CheckNotNull( view, "view" );
            Arguments.CheckNotNull( model, "model" );
            Arguments.CheckNotNull( workQueue, "workQueue" );

            view.Model = model;
            view.GenerateAnimation += OnGenerateAnimation;

            m_View = view;
            m_WorkQueue = workQueue;
            m_Marshaller = new DelegateMarshaller( );
            m_UiProvider = uiProvider;
        }
        public void DoWorkShouldCallWorkerThreadExitingEventWhenThreadIsAborted()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue    = Substitute.For <IWorkItemQueue>();
            IWorkItem        workItem         = Substitute.For <IWorkItem>();

            workItemQueue.Dequeue().Returns(workItem);

            Exception    otherThreadsException            = null;
            bool         workerThreadExitingEventIsCalled = false;
            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.WorkerThreadExiting += (sender, args) =>
            {
                workerThreadExitingEventIsCalled = true;

                try
                {
                    Assert.AreEqual(WorkerThreadExitReason.ThreadAborted, args.WorkerThreadExitReason);
                }
                catch (Exception ex)
                {
                    otherThreadsException = ex;
                }

                manualResetEvent.Set();
            };
            workerThread.Start();

            Wait.While(() => !workerThread.Thread.IsAlive, 300);

            workerThread.Thread.Abort();

            manualResetEvent.WaitOne(500);
            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            Assert.AreEqual(true, workerThreadExitingEventIsCalled);

            if (otherThreadsException != null)
            {
                throw otherThreadsException;
            }
        }
        /// <summary>
        /// Default constructor. Builds low-res cloud textures, and kicks off the high-res generation thread
        /// </summary>
        public CloudCubeMapTextureBuilder( IWorkItemQueue workQueue, int resolution )
        {
            Arguments.CheckNotNull( workQueue, "workQueue" );
            for ( int cloudTextureIndex = 0; cloudTextureIndex < m_CloudTextures.Length; ++cloudTextureIndex )
            {
                m_CloudTextures[ cloudTextureIndex ] = RbGraphics.Factory.CreateCubeMapTexture( );
            }

            //	TODO: AP: Add a first pass that generates low-res bitmaps
            m_WorkQueue = workQueue;
            m_Resolution = resolution;
            CreateFaceBitmaps( resolution );

            AddWorkItem( );
        }
        public void ConstructorShoulStartMinimumCountWorkerThreadsAlthoughThereIsNoWorkItemsInTheQueue()
        {
            IWorkItemQueue workItemQueue = Substitute.For <IWorkItemQueue>();

            workItemQueue.Count.Returns(0);
            workItemQueue.Dequeue().Returns((IWorkItem)null);

            WorkerThreadPool workerThreadPool = new WorkerThreadPool(workItemQueue, 2, 2);

            Assert.AreEqual(2, workerThreadPool.WorkerThreadsCount);

            Wait.While(() => !workerThreadPool.WorkerThreads.All(x => x.Thread.IsAlive), 500);

            Assert.AreEqual(0, workerThreadPool.WorkerThreads.Count(x => x.IsBusy));

            workerThreadPool.Shutdown(true, 500);
        }
        public void DoWorkShouldCallWorkerThreadWorkItemStartingBeforeProcessingWorkItem()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue    = Substitute.For <IWorkItemQueue>();
            IWorkItem        workItem         = Substitute.For <IWorkItem>();

            workItemQueue.Dequeue().Returns(workItem);

            Exception    otherThreadsException = null;
            WorkerThread workerThread          = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.WorkerThreadWorkItemStarting += (sender, args) =>
            {
                try
                {
                    Assert.AreEqual(workItem, args.WorkItem);

                    workItem.DidNotReceive().DoWork();
                }
                catch (Exception ex)
                {
                    otherThreadsException = ex;
                }

                workerThread.Stop();
                manualResetEvent.Set();
            };
            workerThread.Start();

            manualResetEvent.WaitOne(500);
            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            if (otherThreadsException != null)
            {
                throw otherThreadsException;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Ýþçi thread havuzu inþacý metodu.
        /// </summary>
        /// <param name="workItemQueue">Ýþ parçasý kuyruðu.</param>
        /// <param name="minWorkerThreads">Havuzdaki iþçi thread sayýsýnýn en az olabileceði deðer.</param>
        /// <param name="maxWorkerThreads">Havuzdaki iþçi thread sayýsýnýn en fazla olabileceði deðer.</param>
        internal WorkerThreadPool(IWorkItemQueue workItemQueue, int minWorkerThreads, int maxWorkerThreads)
        {
            if (workItemQueue == null)
            {
                throw new ArgumentNullException("workItemQueue");
            }

            EnsureMaxWorkerThreads(minWorkerThreads, maxWorkerThreads);
            EnsureMinWorkerThreads(minWorkerThreads, maxWorkerThreads);

            m_WorkItemQueue    = workItemQueue;
            m_MinWorkerThreads = minWorkerThreads;
            m_MaxWorkerThreads = maxWorkerThreads;
            m_WorkerThreads    = new List <WorkerThread>();

            m_WorkerThreadPoolId    = Interlocked.Increment(ref s_WorkerThreadPoolIdCounter);
            m_CurrentWorkItemsCount = workItemQueue.Count;

            StartOptimumNumberOfThreads();
        }
Esempio n. 15
0
        /// <summary>
        /// İşçi Thread'in yapıcı metodu.
        /// </summary>
        /// <param name="workerThreadManager">İşçi Thread yönetici sınıfı.</param>
        /// <param name="workItemQueue">İş parçası kuyruğu.</param>
        /// <param name="threadName">Thread ismi.</param>
        /// <param name="isBackground">Thread arkaplan Thread'i mi?</param>
        internal WorkerThread(IWorkerThreadManager workerThreadManager, IWorkItemQueue workItemQueue, string threadName, bool isBackground)
        {
            if (workerThreadManager == null)
            {
                throw new ArgumentNullException("workerThreadManager");
            }

            if (workItemQueue == null)
            {
                throw new ArgumentNullException("workItemQueue");
            }

            if (string.IsNullOrWhiteSpace(threadName))
            {
                throw new ArgumentNullException("threadName");
            }

            m_WorkerThreadManager = workerThreadManager;
            m_WorkItemQueue = workItemQueue;
            m_Thread = new Thread(DoWork);
            m_Thread.IsBackground = isBackground;
            m_Thread.Name = threadName;
        }
Esempio n. 16
0
        /// <summary>
        /// İşçi Thread'in yapıcı metodu.
        /// </summary>
        /// <param name="workerThreadManager">İşçi Thread yönetici sınıfı.</param>
        /// <param name="workItemQueue">İş parçası kuyruğu.</param>
        /// <param name="threadName">Thread ismi.</param>
        /// <param name="isBackground">Thread arkaplan Thread'i mi?</param>
        internal WorkerThread(IWorkerThreadManager workerThreadManager, IWorkItemQueue workItemQueue, string threadName, bool isBackground)
        {
            if (workerThreadManager == null)
            {
                throw new ArgumentNullException("workerThreadManager");
            }

            if (workItemQueue == null)
            {
                throw new ArgumentNullException("workItemQueue");
            }

            if (string.IsNullOrWhiteSpace(threadName))
            {
                throw new ArgumentNullException("threadName");
            }

            m_WorkerThreadManager = workerThreadManager;
            m_WorkItemQueue       = workItemQueue;
            m_Thread = new Thread(DoWork);
            m_Thread.IsBackground = isBackground;
            m_Thread.Name         = threadName;
        }
Esempio n. 17
0
 public GetOverviewDayIntent(
     ILogger <GetOverviewDayIntent> logger,
     IMessages messages,
     IKinoheldService kinoheldService,
     IKinoheldDbAccess dbAccess,
     IAmazonService amazonService,
     IWorkItemQueue workItemQueue,
     IEmailService emailService,
     ICinemaDialogWorker cinemaDialogWorker,
     IEmailBodyFormatter <DayOverview> dayOverviewEmailFormatter,
     ISsmlMessageFormatter <DayOverview> dayOverviewSsmlFormatter)
 {
     m_logger                    = logger;
     m_messages                  = messages;
     m_dbAccess                  = dbAccess;
     m_kinoheldService           = kinoheldService;
     m_amazonService             = amazonService;
     m_workItemQueue             = workItemQueue;
     m_emailService              = emailService;
     m_cinemaDialogWorker        = cinemaDialogWorker;
     m_dayOverviewEmailFormatter = dayOverviewEmailFormatter;
     m_dayOverviewSsmlFormatter  = dayOverviewSsmlFormatter;
 }
        public void StartShouldStartThread()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            IWorkItemQueue workItemQueue = Substitute.For <IWorkItemQueue>();

            workItemQueue.Dequeue().Returns((IWorkItem)null);

            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.ShouldExitWorkerThread(workerThread, false).Returns(false);
            workerThread.Start();

            Wait.While(() => !workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(true, workerThread.Thread.IsAlive);

            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);
        }
        public void DoWorkShouldCallWorkItemDequeueWhenWorkerThreadManagerShouldExitWorkerThreadReturnsFalse()
        {
            WorkerThreadManagerStub workerThreadManager = WorkerThreadManagerStub.Create();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            IWorkItemQueue   workItemQueue    = Substitute.For <IWorkItemQueue>();

            workItemQueue.When(x => x.Dequeue()).Do(x => { manualResetEvent.Set(); });

            WorkerThread workerThread = new WorkerThread(workerThreadManager, workItemQueue, "Test", false);

            workerThreadManager.ShouldExitWorkerThread(workerThread, true).Returns(false);
            workerThread.StopWhenWorkItemQueueIsEmpty(true);
            workerThread.Start();

            manualResetEvent.WaitOne(500);
            workerThread.Stop();

            Wait.While(() => workerThread.Thread.IsAlive, 300);

            Assert.AreEqual(false, workerThread.Thread.IsAlive);

            workItemQueue.Received(1).Dequeue();
        }
 public WorkItemQueueService(IWorkItemQueue workItemQueue)
 {
     m_workItemQueue = workItemQueue;
 }
 /// <summary>
 /// Setup constructor. Builds low-res cloud textures, and kicks off the high-res generation thread
 /// </summary>
 public CloudCubeMapTextureBuilder( IWorkItemQueue workQueue )
     : this(workQueue, 512)
 {
 }
        /// <summary>
        /// Creates a default spherical planet
        /// </summary>
        public static ISpherePlanet DefaultPlanet( IWorkItemQueue workQueue, Units.Metres planetRadius )
        {
            workQueue = workQueue ?? ExtendedThreadPool.Instance;

            ISpherePlanet planet = new SpherePlanet( );

            //	Models
            ISpherePlanetModel model = planet.PlanetModel;
            model.Radius				= planetRadius;
            model.OceanModel			= new PlanetOceanModel( );
            model.TerrainModel			= new SpherePlanetProcTerrainModel( );
            model.AtmosphereModel		= new SpherePlanetAtmosphereModel( );
            model.RingModel				= new SpherePlanetRingModel( planetRadius * 1.75, new Units.Metres( 50000 ) );
            model.CloudModel			= new SpherePlanetCloudModel( workQueue );

            //	Renderers
            ISpherePlanetRenderer renderer = planet.PlanetRenderer;
            renderer.MarbleRenderer		= new SpherePlanetMarbleRenderer( new SpherePlanetMarbleTextureBuilder( ) );
            renderer.OceanRenderer		= new SpherePlanetOceanRenderer( );
            renderer.TerrainRenderer	= new SpherePlanetTerrainPatchRenderer( );
            renderer.AtmosphereRenderer = new SpherePlanetAtmosphereRenderer( );
            renderer.RingRenderer		= new SpherePlanetRingRenderer( );
            renderer.CloudRenderer		= new SpherePlanetCloudRenderer( );

            return planet;
        }
        /// <summary>
        /// Ýþçi thread havuzu inþacý metodu.
        /// </summary>
        /// <param name="workItemQueue">Ýþ parçasý kuyruðu.</param>
        /// <param name="minWorkerThreads">Havuzdaki iþçi thread sayýsýnýn en az olabileceði deðer.</param>
        /// <param name="maxWorkerThreads">Havuzdaki iþçi thread sayýsýnýn en fazla olabileceði deðer.</param>
        internal WorkerThreadPool(IWorkItemQueue workItemQueue, int minWorkerThreads, int maxWorkerThreads)
        {
            if (workItemQueue == null)
            {
                throw new ArgumentNullException("workItemQueue");
            }

            EnsureMaxWorkerThreads(minWorkerThreads, maxWorkerThreads);
            EnsureMinWorkerThreads(minWorkerThreads, maxWorkerThreads);

            m_WorkItemQueue = workItemQueue;
            m_MinWorkerThreads = minWorkerThreads;
            m_MaxWorkerThreads = maxWorkerThreads;
            m_WorkerThreads = new List<WorkerThread>();

            m_WorkerThreadPoolId = Interlocked.Increment(ref s_WorkerThreadPoolIdCounter);
            m_CurrentWorkItemsCount = workItemQueue.Count;

            StartOptimumNumberOfThreads();
        }
 /// <summary>
 /// Sets the internal queue that actually executes the work items on Start()
 /// </summary>
 public DeferredWorkItemQueue( IWorkItemQueue internalQueue )
 {
     m_Queue = internalQueue;
 }