示例#1
0
        public void TwoWIGsStartSuspended()
        {
            SmartThreadPool stp = new SmartThreadPool();

            WIGStartInfo wigStartInfo = new WIGStartInfo();

            wigStartInfo.StartSuspended = true;

            IWorkItemsGroup wig1 = stp.CreateWorkItemsGroup(10, wigStartInfo);
            IWorkItemsGroup wig2 = stp.CreateWorkItemsGroup(10, wigStartInfo);

            wig1.QueueWorkItem(new WorkItemCallback(this.DoWork));
            wig2.QueueWorkItem(new WorkItemCallback(this.DoWork));

            Assert.IsFalse(wig1.WaitForIdle(200));
            Assert.IsFalse(wig2.WaitForIdle(200));

            wig1.Start();

            Assert.IsTrue(wig1.WaitForIdle(200));
            Assert.IsFalse(wig2.WaitForIdle(200));

            wig2.Start();

            Assert.IsTrue(wig1.WaitForIdle(0));
            Assert.IsTrue(wig2.WaitForIdle(200));
        }
示例#2
0
        public void STPAndWIGStartSuspended()
        {
            STPStartInfo stpStartInfo = new STPStartInfo();

            stpStartInfo.StartSuspended = true;

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);

            WIGStartInfo wigStartInfo = new WIGStartInfo();

            wigStartInfo.StartSuspended = true;

            IWorkItemsGroup wig = stp.CreateWorkItemsGroup(10, wigStartInfo);

            wig.QueueWorkItem(new WorkItemCallback(this.DoWork));

            Assert.IsFalse(wig.WaitForIdle(200));

            wig.Start();

            Assert.IsFalse(wig.WaitForIdle(200));

            stp.Start();

            Assert.IsTrue(wig.WaitForIdle(5000), "WIG is not idle");
            Assert.IsTrue(stp.WaitForIdle(5000), "STP is not idle");
        }
        public void Dispose()
        {
            IsActive = false;
            ThreadPool2.WaitForIdle();

            if (Player != null)
            {
                Player.Dispose();
            }

            Core.TcpClientCollection.Remove(TcpClient);

            if (TcpClient != null)
            {
                TcpClient.Close();
            }
            if (Reader != null)
            {
                Reader.Dispose();
            }
            if (Writer != null)
            {
                Writer.Dispose();
            }

            Thread.Dispose();
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallStatPostPrio(IWorkItemsGroup wig)
        {
            bool   postExecuteCalled = false;
            object state             = new object();
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = delegate(IWorkItemResult w) { postExecuteCalled = true; };
            WorkItemInfo wii = new WorkItemInfo();

            wii.WorkItemPriority            = WorkItemPriority.BelowNormal;
            wii.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);

            IWorkItemResult wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                WorkItemPriority.BelowNormal);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);
        }
        private object DoWaitForIdle(object state)
        {
            IWorkItemsGroup workItemsGroup = state as IWorkItemsGroup;

            workItemsGroup.WaitForIdle();
            return(null);
        }
        /// <summary>
        /// QuickSort array using wig to parallel the sort
        /// </summary>
        /// <param name="wig">A IWorkItemsGroup to use to parallel the sort</param>
        /// <param name="array">The array of items to sort</param>
        public static void QuickSort(IWorkItemsGroup wig, int[] array)
        {
            // Initiate the QuickSort
            wig.QueueWorkItem(QuickSort, wig, array, 0, array.Length - 1);

            // Wait for the sort to complete.
            wig.WaitForIdle();
        }
        /// <summary>
        /// QuickSort array using wig to parallel the sort
        /// </summary>
        /// <param name="wig">A IWorkItemsGroup to use to parallel the sort</param>
        /// <param name="array">The array of items to sort</param>
        public static void QuickSort(IWorkItemsGroup wig, int[] array)
        {
            // Initiate the QuickSort
            wig.QueueWorkItem(QuickSort, wig, array, 0, array.Length - 1);

            // Wait for the sort to complete.
            wig.WaitForIdle();
        }
        public void WIGStartSuspended()
        {
            STP stp = new STP();

            WIGStartInfo wigStartInfo = new WIGStartInfo
            {
                StartSuspended = true
            };

            IWorkItemsGroup wig = stp.CreateWorkItemsGroup(10, wigStartInfo);

            wig.QueueWorkItem(new WorkItemCallback(this.DoWork));

            Assert.IsFalse(wig.WaitForIdle(200));

            wig.Start();

            Assert.IsTrue(wig.WaitForIdle(200));
        }
示例#9
0
        private void DoUpdateProjectsInternal()
        {
            IDictionary <Server, ISet <Project> > projectsByServer = ConfigurationService.GetProjects();
            var allWorkItemsGroup     = new List <IWorkItemsGroup>();
            var allFutureBuildDetails = new Dictionary <Project, IWorkItemResult>();

            foreach (KeyValuePair <Server, ISet <Project> > pair in projectsByServer)
            {
                Server         server   = pair.Key;
                ISet <Project> projects = pair.Value;

                IWorkItemsGroup workItemsGroup = threadPool.CreateWorkItemsGroup(THREAD_COUNT_BY_DOMAIN);
                allWorkItemsGroup.Add(workItemsGroup);

                foreach (Project project in projects)
                {
                    WorkItemCallback work = delegate(object state)
                    {
                        AllBuildDetails newBuildDetail = null;
                        try
                        {
                            Project project_ = (Project)state;
                            newBuildDetail = HudsonService.UpdateProject(project_);
                        }
                        catch (Exception ex)
                        {
                            LoggingHelper.LogError(logger, ex);
                        }
                        return(newBuildDetail);
                    };
                    IWorkItemResult futureRes = workItemsGroup.QueueWorkItem(work, project);
                    allFutureBuildDetails[project] = futureRes;
                }
            }

            foreach (IWorkItemsGroup workItemsGroup in allWorkItemsGroup)
            {
                workItemsGroup.WaitForIdle();
            }

            foreach (ISet <Project> projects in projectsByServer.Values)
            {
                foreach (Project project in projects)
                {
                    IWorkItemResult newStatus;
                    allFutureBuildDetails.TryGetValue(project, out newStatus);
                    project.AllBuildDetails = newStatus != null ? (AllBuildDetails)newStatus.Result : null;
                }
            }

            if (ProjectsUpdated != null)
            {
                ProjectsUpdated();
            }
        }
示例#10
0
        public void GoodCallback()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            workItemsGroup.QueueWorkItem(new WorkItemCallback(DoWork));

            workItemsGroup.WaitForIdle();

            smartThreadPool.Shutdown();
        }
        public void WaitForIdle()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(10 * 1000, 25, 0);
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            ManualResetEvent isRunning = new ManualResetEvent(false);

            for (int i = 0; i < 4; ++i)
            {
                workItemsGroup.QueueWorkItem(delegate { isRunning.WaitOne(); });
            }

            bool success = !workItemsGroup.WaitForIdle(1000);

            isRunning.Set();

            success = success && workItemsGroup.WaitForIdle(1000);

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
        internal void Dispose()
        {
            if (IsActive)
            {
                IsActive = false;
                ThreadPool.WaitForIdle();

                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }
        }
示例#13
0
        public void GoodPostExecute()
        {
            STP             smartThreadPool = new STP();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            workItemsGroup.QueueWorkItem(
                new WorkItemCallback(DoWork),
                null,
                new PostExecuteWorkItemCallback(DoPostExecute));

            workItemsGroup.WaitForIdle();

            smartThreadPool.Shutdown();
        }
示例#14
0
        public void Join(IEnumerable <Action> actions)
        {
            WIGStartInfo wigStartInfo = new WIGStartInfo
            {
                StartSuspended = true
            };
            IWorkItemsGroup workItemsGroup = this.CreateWorkItemsGroup(2147483647, wigStartInfo);

            foreach (Action current in actions)
            {
                workItemsGroup.QueueWorkItem(current);
            }
            workItemsGroup.Start();
            workItemsGroup.WaitForIdle();
        }
示例#15
0
        public void ChainedDelegatesCallback()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            WorkItemCallback workItemCallback = new WorkItemCallback(DoWork);

            workItemCallback += new WorkItemCallback(DoWork);

            workItemsGroup.QueueWorkItem(workItemCallback);

            workItemsGroup.WaitForIdle();

            smartThreadPool.Shutdown();
        }
示例#16
0
        public void ChainedDelegatesCallback()
        {
            Assert.Throws <NotSupportedException>(() =>
            {
                SmartThreadPool smartThreadPool = new SmartThreadPool();
                IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

                WorkItemCallback workItemCallback = new WorkItemCallback(DoWork);
                workItemCallback += new WorkItemCallback(DoWork);

                workItemsGroup.QueueWorkItem(workItemCallback);

                workItemsGroup.WaitForIdle();

                smartThreadPool.Shutdown();
            });
        }
        public void WaitForIdleWithCancel()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(10 * 1000, 1, 1);
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(2);

            _x = 0;

            IWorkItemResult wir1 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);
            IWorkItemResult wir2 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);
            IWorkItemResult wir3 = workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), 1000);

            while (0 == _x)
            {
                Thread.Sleep(10);
            }

            //Console.WriteLine("{0}: Cancelling WIG", DateTime.Now.ToLongTimeString());
            workItemsGroup.Cancel();

            // At this point:
            // The first work item is running
            // The second work item is cancelled, but waits in the STP queue
            // The third work item is cancelled.

            Assert.AreEqual(1, _x);

            Assert.IsTrue(wir2.IsCanceled);

            Assert.IsTrue(wir3.IsCanceled);

            // Make sure the workItemsGroup is still idle
            Assert.IsFalse(workItemsGroup.IsIdle);

            //Console.WriteLine("{0}: Waiting for 1st result", DateTime.Now.ToLongTimeString());
            wir1.GetResult();

            Assert.AreEqual(2, _x);

            bool isIdle = workItemsGroup.WaitForIdle(100);

            Assert.IsTrue(isIdle);

            smartThreadPool.Shutdown();
        }
        public void DoWork(object [] states)
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            // Create a work items group that processes
            // one work item at a time
            IWorkItemsGroup wig = smartThreadPool.CreateWorkItemsGroup(1);

            // Queue some work items
            foreach (object state in states)
            {
                wig.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), state);
            }

            // Wait for the completion of all work items in the work items group
            wig.WaitForIdle();

            smartThreadPool.Shutdown();
        }
示例#19
0
        public void Pipe <T>(T pipeState, IEnumerable <Action <T> > actions)
        {
            WIGStartInfo wigStartInfo = new WIGStartInfo
            {
                StartSuspended = true
            };
            IWorkItemsGroup workItemsGroup = this.CreateWorkItemsGroup(2147483647, wigStartInfo);

            foreach (Action <T> current in actions)
            {
                Action <T> act = current;
                workItemsGroup.QueueWorkItem(delegate
                {
                    act(pipeState);
                });
            }
            workItemsGroup.Start();
            workItemsGroup.WaitForIdle();
        }
示例#20
0
        public void ChainedDelegatesPostExecute()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            PostExecuteWorkItemCallback postExecuteWorkItemCallback =
                new PostExecuteWorkItemCallback(DoPostExecute);

            postExecuteWorkItemCallback +=
                new PostExecuteWorkItemCallback(DoPostExecute);

            workItemsGroup.QueueWorkItem(
                new WorkItemCallback(DoWork),
                null,
                postExecuteWorkItemCallback);

            workItemsGroup.WaitForIdle();

            smartThreadPool.Shutdown();
        }
        //IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback);
        public static void TestQueueWorkItemInfoCall(IWorkItemsGroup wig)
        {
            WorkItemInfo wii = new WorkItemInfo();

            wii.CallToPostExecute           = CallToPostExecute.Never;
            wii.DisposeOfStateObjects       = true;
            wii.PostExecuteWorkItemCallback = delegate(IWorkItemResult w) { };
            wii.UseCallerCallContext        = true;
            wii.UseCallerHttpContext        = true;
            wii.WorkItemPriority            = WorkItemPriority.Highest;

            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii);

            IWorkItemResult wir = wig.QueueWorkItem(wii, wiic.CompareWorkItemInfo);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
示例#22
0
        public void ChainedDelegatesPostExecute()
        {
            Assert.ThrowsException <NotSupportedException>(() =>
            {
                STP smartThreadPool            = new STP();
                IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

                PostExecuteWorkItemCallback postExecuteWorkItemCallback =
                    new PostExecuteWorkItemCallback(DoPostExecute);
                postExecuteWorkItemCallback +=
                    new PostExecuteWorkItemCallback(DoPostExecute);

                workItemsGroup.QueueWorkItem(
                    new WorkItemCallback(DoWork),
                    null,
                    postExecuteWorkItemCallback);

                workItemsGroup.WaitForIdle();

                smartThreadPool.Shutdown();
            });
        }
示例#23
0
        public void BuildAllContent()
        {
            LoadOldContentFiles();
            LoadNewContentFiles();

            Program.ContentCollection.ContentFiles.ForEach(a => ThreadPool.QueueWorkItem(() => a.BuildContent()));
            ThreadPool.WaitForIdle();

            Program.ContentCollection.ContentFiles = Program.ContentCollection.ContentFiles.Where(a => !a.DeleteFlag).ToList();

            if (Program.ContentCollection.ContentFiles.Any(a => a.RebuildFlag))
            {
                Program.ContentCollection.Serialize($"{Program.Arguments.IntermediateDirectory}/Content.yml".GetFullPath());

                foreach (string dir in Directory.GetDirectories(Program.Arguments.OutputDirectory, "*", SearchOption.AllDirectories))
                {
                    if (Directory.Exists(dir))
                    {
                        bool CanDelete = true;

                        foreach (string file in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
                        {
                            if (File.Exists(file))
                            {
                                CanDelete = false;
                                break;
                            }
                        }

                        if (CanDelete)
                        {
                            Directory.Delete(dir, true);
                        }
                    }
                }
            }
        }
示例#24
0
        public void DoWork(object [] states)
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            WIGStartInfo wigStartInfo = new WIGStartInfo();

            wigStartInfo.StartSuspended = true;

            IWorkItemsGroup wig = smartThreadPool.CreateWorkItemsGroup(1, wigStartInfo);

            foreach (object state in states)
            {
                wig.QueueWorkItem(new
                                  WorkItemCallback(this.DoSomeWork), state);
            }

            // Start working on the work items in the work items group queue
            wig.Start();

            // Wait for the completion of all work items
            wig.WaitForIdle();

            smartThreadPool.Shutdown();
        }
        public void DisposeCallerState()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            WIGStartInfo wigStartInfo = new WIGStartInfo();

            wigStartInfo.DisposeOfStateObjects = true;

            IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(int.MaxValue, wigStartInfo);

            CallerState nonDisposableCallerState = new NonDisposableCallerState();
            CallerState disposableCallerState    = new DisposableCallerState();

            IWorkItemResult wir1 =
                workItemsGroup.QueueWorkItem(
                    new WorkItemCallback(this.DoSomeWork),
                    nonDisposableCallerState);

            IWorkItemResult wir2 =
                workItemsGroup.QueueWorkItem(
                    new WorkItemCallback(this.DoSomeWork),
                    disposableCallerState);

            wir1.GetResult();
            Assert.AreEqual(1, nonDisposableCallerState.Value);

            wir2.GetResult();

            // Wait a little bit for the working thread to call dispose on the
            // work item's state.
            workItemsGroup.WaitForIdle();

            Assert.AreEqual(2, disposableCallerState.Value);

            smartThreadPool.Shutdown();
        }
示例#26
0
        private void DoUpdateProjectsInternal()
        {
            IDictionary <Server, ISet <Project> > projectsByServer = ConfigurationService.GetProjects();
            var allWorkItemsGroup     = new List <IWorkItemsGroup>();
            var allFutureBuildDetails = new Dictionary <Project, IWorkItemResult>();

            foreach (KeyValuePair <Server, ISet <Project> > pair in projectsByServer)
            {
                Server         server   = pair.Key;
                ISet <Project> projects = pair.Value;

                IWorkItemsGroup workItemsGroup = threadPool.CreateWorkItemsGroup(THREAD_COUNT_BY_DOMAIN);
                allWorkItemsGroup.Add(workItemsGroup);

                foreach (Project project in projects)
                {
                    WorkItemCallback work = delegate(object state)
                    {
                        AllBuildDetails newBuildDetail = null;
                        try
                        {
                            Project project_ = (Project)state;
                            newBuildDetail = JenkinsService.UpdateProject(project_);
                        }
                        catch (Exception ex)
                        {
                            LoggingHelper.LogError(logger, ex);
                        }
                        return(newBuildDetail);
                    };
                    IWorkItemResult futureRes = workItemsGroup.QueueWorkItem(work, project);
                    allFutureBuildDetails[project] = futureRes;
                }
            }

            foreach (IWorkItemsGroup workItemsGroup in allWorkItemsGroup)
            {
                workItemsGroup.WaitForIdle();
            }

            foreach (ISet <Project> projects in projectsByServer.Values)
            {
                foreach (Project project in projects)
                {
                    IWorkItemResult newStatus;
                    allFutureBuildDetails.TryGetValue(project, out newStatus);
                    AllBuildDetails previousAllBuildDetails = project.AllBuildDetails;
                    if (newStatus != null)
                    {
                        project.AllBuildDetails      = (AllBuildDetails)newStatus.Result;
                        project.Activity.HasNewBuild = false;

                        if (previousAllBuildDetails != null && project.AllBuildDetails != null)
                        {
                            project.PreviousStatus = previousAllBuildDetails.Status;

                            if (previousAllBuildDetails.LastBuild != null && project.AllBuildDetails.LastBuild != null)
                            {
                                //  Has existing LastBuilds
                                if (previousAllBuildDetails.LastBuild.Number != project.AllBuildDetails.LastBuild.Number)
                                {
                                    project.Activity.HasNewBuild = true;
                                }
                            }
                            else if (previousAllBuildDetails.LastBuild == null && project.AllBuildDetails.LastBuild != null)
                            {
                                //  1st new LastBuild is found
                                project.Activity.HasNewBuild = true;
                            }
                        }
                    }
                }
            }

            if (ProjectsUpdated != null)
            {
                ProjectsUpdated();
            }
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallStatPostPflgPrio(IWorkItemsGroup wig)
        {
            bool postExecuteCalled;
            CallToPostExecute           callToPostExecute;
            object                      state = new object();
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = delegate(IWorkItemResult w) { postExecuteCalled = true; };
            WorkItemInfo                wii = new WorkItemInfo();

            wii.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);
            WorkItemPriority     workItemPriority;
            IWorkItemResult      wir;
            bool success;

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.Always;
            workItemPriority  = WorkItemPriority.Lowest;

            // Check without cancel
            postExecuteCalled = false;
            wiic.SleepTime    = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority  = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);

            // Check with cancel
            success           = false;
            postExecuteCalled = false;
            wiic.SleepTime    = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsTrue(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.Never;
            workItemPriority  = WorkItemPriority.Highest;

            postExecuteCalled = false;
            wiic.SleepTime    = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority  = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsFalse(postExecuteCalled);

            // Check with cancel
            success           = false;
            postExecuteCalled = false;
            wiic.SleepTime    = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsFalse(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.WhenWorkItemNotCanceled;
            workItemPriority  = WorkItemPriority.AboveNormal;

            postExecuteCalled = false;
            wiic.SleepTime    = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority  = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);

            // Check with cancel
            success           = false;
            postExecuteCalled = false;
            wiic.SleepTime    = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsFalse(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);


            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.WhenWorkItemCanceled;
            workItemPriority  = WorkItemPriority.BelowNormal;

            postExecuteCalled = false;
            wiic.SleepTime    = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority  = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsFalse(postExecuteCalled);

            // Check with cancel
            success           = false;
            postExecuteCalled = false;
            wiic.SleepTime    = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsTrue(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);
        }
示例#28
0
        /// <summary>
        /// Sends the email to recipients.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="documents">The updated documents.</param>
        public void SendEmailToRecipients(string site, int batchId)
        {
            try
            {
                List <Subscription> subscribers = SubscriptionService.GetCurrentSubscribers(site);
                if (null == subscribers || subscribers.Count == 0)
                {
                    log.Info("No Subscribers - email will not be sent");
                    return;
                }
                string emailTemplateURL = null;
                string emailSubject     = null;
                using (NotificationTablesDataContext dataContext = new NotificationTablesDataContext())
                {
                    SiteConfiguration siteConfiguration = dataContext.SiteConfigurations.FirstOrDefault(siteName => siteName.site == site);
                    emailTemplateURL = siteConfiguration.emailTemplateURL;
                    emailSubject     = siteConfiguration.siteName + " " + (ConfigurationManager.AppSettings["Email.Subject"] as String);
                }

                string messageBody = GetEmailBody(emailTemplateURL + "?batchId=" + batchId);

                SmartThreadPool smartThreadPool = new SmartThreadPool();

                IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(maxThreads);

                foreach (Subscription subscription in subscribers)
                {
                    Email email = new Email
                    {
                        to      = subscription.email,
                        from    = FromAddress,
                        body    = messageBody,
                        subject = emailSubject
                    };

                    PostExecuteWorkItemCallback afterEmailSend = delegate
                    {
                        SaveSentMailInformation(site, batchId, email);
                    };

                    WorkItemInfo workItem = new WorkItemInfo();
                    workItem.PostExecuteWorkItemCallback = afterEmailSend;
                    workItemsGroup.QueueWorkItem(workItem, SendMail, email);
                }

                workItemsGroup.WaitForIdle();

                smartThreadPool.Shutdown();

                using (NotificationTablesDataContext dataContext = new NotificationTablesDataContext())
                {
                    Batch batch = dataContext.Batches.FirstOrDefault(b => b.site == site && b.batchId == batchId);

                    batch.finishDate = DateTime.Now;
                    batch.status     = "Successful";

                    dataContext.SubmitChanges();
                }
            }
            catch (Exception e)
            {
                log.Error("Unable to Send Email", e);
                using (NotificationTablesDataContext dataContext = new NotificationTablesDataContext())
                {
                    Batch batch = dataContext.Batches.FirstOrDefault(b => b.site == site && b.batchId == batchId);

                    batch.status = "Unsuccessful";

                    dataContext.SubmitChanges();
                }
                throw e;
            }
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallStatPostPflgPrio(IWorkItemsGroup wig)
        {
            bool postExecuteCalled;
            CallToPostExecute callToPostExecute;
            object state = new object();
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = delegate(IWorkItemResult w) { postExecuteCalled = true; };
            WorkItemInfo wii = new WorkItemInfo();
            wii.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);
            WorkItemPriority workItemPriority;
            IWorkItemResult wir;
            bool success;

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.Always;
            workItemPriority = WorkItemPriority.Lowest;

            // Check without cancel
            postExecuteCalled = false;
            wiic.SleepTime = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);

            // Check with cancel
            success = false;
            postExecuteCalled = false;
            wiic.SleepTime = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsTrue(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.Never;
            workItemPriority = WorkItemPriority.Highest;

            postExecuteCalled = false;
            wiic.SleepTime = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute, 
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsFalse(postExecuteCalled);

            // Check with cancel
            success = false;
            postExecuteCalled = false;
            wiic.SleepTime = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsFalse(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);

            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.WhenWorkItemNotCanceled;
            workItemPriority = WorkItemPriority.AboveNormal;

            postExecuteCalled = false;
            wiic.SleepTime = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);

            // Check with cancel
            success = false;
            postExecuteCalled = false;
            wiic.SleepTime = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsFalse(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);


            /////////////////////////////////////////////////////////////////////////////

            callToPostExecute = CallToPostExecute.WhenWorkItemCanceled;
            workItemPriority = WorkItemPriority.BelowNormal;

            postExecuteCalled = false;
            wiic.SleepTime = 0;

            wii.CallToPostExecute = callToPostExecute;
            wii.WorkItemPriority = workItemPriority;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsFalse(postExecuteCalled);

            // Check with cancel
            success = false;
            postExecuteCalled = false;
            wiic.SleepTime = 100;

            wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback,
                callToPostExecute,
                workItemPriority);

            wir.Cancel();

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            Assert.IsTrue(postExecuteCalled);

            try
            {
                wir.GetResult();
            }
            catch (WorkItemCancelException ce)
            {
                success = true;
            }

            Assert.IsTrue(success);
        }
        //IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state);
        public static void TestQueueWorkItemInfoCallStat(IWorkItemsGroup wig)
        {
            object state = new object();
            WorkItemInfo wii = new WorkItemInfo();
            wii.CallToPostExecute = CallToPostExecute.Never;
            wii.DisposeOfStateObjects = true;
            wii.PostExecuteWorkItemCallback = delegate(IWorkItemResult w) { };
            wii.UseCallerCallContext = true;
            wii.UseCallerHttpContext = true;
            wii.WorkItemPriority = WorkItemPriority.Highest;

            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);

            IWorkItemResult wir = wig.QueueWorkItem(wii, wiic.CompareWorkItemInfo, state);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallStatPostPrio(IWorkItemsGroup wig)
        {
            bool postExecuteCalled = false;
            object state = new object();
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = delegate(IWorkItemResult w) { postExecuteCalled = true; };
            WorkItemInfo wii = new WorkItemInfo();
            wii.WorkItemPriority = WorkItemPriority.BelowNormal;
            wii.PostExecuteWorkItemCallback = postExecuteWorkItemCallback;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);

            IWorkItemResult wir = wig.QueueWorkItem(
                wiic.CompareWorkItemInfo,
                state,
                postExecuteWorkItemCallback, 
                WorkItemPriority.BelowNormal);

            // We must wait for idle to let the post execute run
            wig.WaitForIdle();

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);
        }
        public override void PostApply(BackgroundWorker worker, DoWorkEventArgs e)
        {
            try
            {
                Dictionary <string, string> error = new Dictionary <string, string>();
                List <string> successful          = new List <string>();

                int num = 0;
                progressStepCount = 5;

                List <DriverPackage> driverPackages = (List <DriverPackage>)UserData["DriverPackageItems"];
                totalDriverPackages = driverPackages.Count;

                foreach (DriverPackage driverPackage in driverPackages)
                {
                    progressStart = num * 100 / totalDriverPackages;
                    worker.ReportProgress(progressStart, string.Format("Importing Driver Package: {0}", driverPackage.Name));

                    if (driverPackage.Create())
                    {
                        string objectPath = null;
                        refreshPackage = false;
                        refreshDP      = false;
                        progressTotal  = 0;
                        progressCount  = 0;

                        try
                        {
                            SmartThreadPool smartThreadPool = new SmartThreadPool();
                            // lock driver packge object
                            objectPath = driverPackage.Package["__RELPath"].StringValue;
                            Utility.RequestLock(ConnectionManager, objectPath);

                            int totalInfs = driverPackage.Infs.Length;
                            int num2      = 1;
                            // parse ini files and create a dictinonary with the results
                            log.Debug("ProcessingINFs ---- ");
                            foreach (string inf in driverPackage.Infs)
                            {
                                // I still hate calculating progress bars
                                progresPercent = (num2 / totalInfs * 100) / progressStepCount / totalDriverPackages;
                                worker.ReportProgress(
                                    progressStart + (progresPercent),
                                    string.Format("Importing Driver Package: {0}\n - processing inf '{1}'", driverPackage.Name, Path.GetFileName(inf))
                                    );

                                log.Debug("ProcessingINF: " + inf);
                                Driver driver = new Driver(inf);
                                if (driver.HasWarning)
                                {
                                    driverPackage.ImportWarning[inf] = driver.Warning.Message;
                                }
                                else if (driver.HasException)
                                {
                                    driverPackage.ImportError[inf] = driver.Exception.Message;
                                }
                                else
                                {
                                    // need to check versions to for duplicate drivers with differnt version number
                                    driverPackage.Drivers[Path.GetFileName(inf) + driver.Version] = driver;
                                }

                                num2++;
                            }
                            // I still hate calculating progress bars
                            progressStepPercent = progresPercent;
                            progresPercent      = 100 / progressStepCount / totalDriverPackages * 2;
                            log.Debug("ProcessingDrivers ---- ");
                            // check if driver is in driver package and same version
                            foreach (IResultObject driverObject in driverPackage.GetDriversInPackge())
                            {
                                // thread this so it is faster
                                smartThreadPool.QueueWorkItem(new Amib.Threading.Func <DriverPackage, IResultObject, BackgroundWorker, bool>(ProcessDrivers), driverPackage, driverObject, worker);
                            }
                            // wait for thread pool to finish
                            smartThreadPool.WaitForIdle();
                            // I still hate calculating progress bars
                            progressStepPercent = progresPercent;
                            log.Debug("ImportingDrivers ---- ");

                            // tried to create threading for importing drivers but CreateFromINF go sad if it gets to many request, so will leave this code here for maybe one day I fix it
                            IWorkItemsGroup workItemsGroup = smartThreadPool.CreateWorkItemsGroup(1);

                            foreach (KeyValuePair <string, Driver> driver in driverPackage.Drivers)
                            {
                                if (driver.Value.Import)
                                {
                                    ++progressTotal;
                                    workItemsGroup.QueueWorkItem(new Amib.Threading.Func <DriverPackage, Driver, BackgroundWorker, bool>(ImportDrivers), driverPackage, driver.Value, worker);
                                }
                            }
                            // wait for thread pool to finish
                            workItemsGroup.WaitForIdle();

                            smartThreadPool.Shutdown();

                            if (refreshPackage)
                            {
                                log.Debug("RefreshPackage ---- ");
                                // I still hate calculating progress bars
                                progresPercent = 100 / progressStepCount / totalDriverPackages * 4;
                                worker.ReportProgress(progressStart + (progresPercent), string.Format("Importing Driver Package: {0}\n - adding drivers to package", driverPackage.Name));
                                // add all drivers in the drivers list to the driver package
                                driverPackage.AddDriversToDriverPack();
                            }

                            if (refreshDP)
                            {
                                log.Debug("RefreshDP ---- ");
                                // I still hate calculating progress bars
                                progresPercent = 100 / progressStepCount / totalDriverPackages * 5;
                                worker.ReportProgress(progressStart + (progresPercent), string.Format("Importing Driver Package: {0}\n - updating distribution point", driverPackage.Name));
                                driverPackage.Package.ExecuteMethod("RefreshPkgSource", null);
                            }

                            log.Debug("CreateHashFile ---- ");
                            driverPackage.CreateHashFile();
                            log.Debug("UpdatePackageVersion ---- ");
                            driverPackage.UpdatePackageVersion();
                        }
                        finally
                        {
                            // unlock driver package object
                            Utility.ReleaseLock(ConnectionManager, objectPath);
                        }
                    }
                    ++num;
                }

                PrepareCompletion();
                base.PostApply(worker, e);
            }
            catch (Exception ex)
            {
                AddRefreshResultObject(null, PropertyDataUpdateAction.RefreshAll);
                PrepareError(ex.Message);
            }
        }