/// <summary>
        /// Sort a subarray in array, starting with the left item and ending in the right item.
        /// The method uses the IWorkItemsGroup 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>
        /// <param name="left">The left index in the subarray</param>
        /// <param name="right">The right index in the subarray</param>
        private static void QuickSort(IWorkItemsGroup wig, int[] array, int left, int right)
        {
            if (right > left)
            {
                int pivotIndex = left;
                int pivotNewIndex = Partition(array, left, right, pivotIndex);

                wig.QueueWorkItem(QuickSort, wig, array, left, pivotNewIndex - 1);
                wig.QueueWorkItem(QuickSort, wig, array, pivotNewIndex + 1, right);
            }
        }
        /// <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();
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback);
        public static void TestQueueWorkItemCall(IWorkItemsGroup wig)
        {
            WorkItemInfo wii = new WorkItemInfo();
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii);

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

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state);
        public static void TestQueueWorkItemCallStat(IWorkItemsGroup wig)
        {
            object state = new object();
            WorkItemInfo wii = new WorkItemInfo();
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);

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

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallPrio(IWorkItemsGroup wig)
        {
            WorkItemInfo wii = new WorkItemInfo();
            wii.WorkItemPriority = WorkItemPriority.AboveNormal;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii);

            IWorkItemResult wir = wig.QueueWorkItem((WorkItemCallback)wiic.CompareWorkItemInfo, WorkItemPriority.AboveNormal);

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
        }
        //IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority);
        public static void TestQueueWorkItemCallStatPrio(IWorkItemsGroup wig)
        {
            object state = new object();
            WorkItemInfo wii = new WorkItemInfo();
            wii.WorkItemPriority = WorkItemPriority.AboveNormal;
            WorkItemInfoComparer wiic = new WorkItemInfoComparer(wii, state);

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

            bool success = (bool)wir.Result;

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

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

            // 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 void WaitAnyWithTimeoutSuccess()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            bool success;

            IWorkItemResult [] wirs = new IWorkItemResult[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] =
                    workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);
            }

            int index = SmartThreadPool.WaitAny(wirs, 1500, true);

            success = (index != WaitHandle.WaitTimeout);

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
示例#9
0
        public void Timeout()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();
            IWorkItemsGroup workItemsGroup  = smartThreadPool.CreateWorkItemsGroup(int.MaxValue);

            bool success = false;

            IWorkItemResult wir =
                workItemsGroup.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);

            try
            {
                wir.GetResult(500, true);
            }
            catch (WorkItemTimeoutException)
            {
                success = true;
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
示例#10
0
        private object ThreadPreHandlePackage(object p)
        {
            if (string.IsNullOrEmpty((string)p))
            {
                if (IsActive)
                {
                    IsActive = false;
                    Core.RCONPlayer.Remove(Client, "You have left the server.");
                }
            }
            else
            {
                Package Package = new Package((string)p, Client);
                if (Package.IsValid)
                {
                    LastValidPing = DateTime.Now;
                    ThreadPool2.QueueWorkItem(new WorkItemCallback(ThreadHandlePackage), Package);
                    Core.Logger.Log($"Receive: {Package.ToString()}", Logger.LogTypes.Debug, Client);
                }
            }

            return(null);
        }
        //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);
        public static void TestQueueWorkItemCallStatPost(IWorkItemsGroup wig)
        {
            bool   postExecuteCalled = false;
            object state             = new object();
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = delegate(IWorkItemResult w) { postExecuteCalled = true; };
            WorkItemInfo wii = new WorkItemInfo();

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

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

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

            bool success = (bool)wir.Result;

            Assert.IsTrue(success);
            Assert.IsTrue(postExecuteCalled);
        }
示例#13
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);
                        }
                    }
                }
            }
        }
示例#14
0
        public void Cancel1WIGof2WorkItems()
        {
            int counter1 = 0;
            int counter2 = 0;

            SmartThreadPool stp  = new SmartThreadPool();
            IWorkItemsGroup wig1 = stp.CreateWorkItemsGroup(3);
            IWorkItemsGroup wig2 = stp.CreateWorkItemsGroup(3);

            for (int i = 0; i < 3; i++)
            {
                wig1.QueueWorkItem(
                    state => { Interlocked.Increment(ref counter1); Thread.Sleep(500); Interlocked.Increment(ref counter1); return(null); }
                    );
            }

            for (int i = 0; i < 3; i++)
            {
                wig2.QueueWorkItem(
                    state => { Thread.Sleep(500); Interlocked.Increment(ref counter2); return(null); }
                    );
            }

            while (counter1 < 3)
            {
                Thread.Sleep(1);
            }
            wig1.Cancel(true);

            stp.WaitForIdle();

            Assert.AreEqual(3, counter1, "Cancelled WIG1");
            Assert.AreEqual(3, counter2, "Normal WIG2");

            stp.Shutdown();
        }
示例#15
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();
        }
示例#16
0
        public void CancelWIGWorkItems()
        {
            // I don't use lock on the counter, since any number above 0 is a failure.
            // In the worst case counter will be equal to 1 which is still not 0.
            int counter = 0;

            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemsGroup wig = stp.CreateWorkItemsGroup(10);

            for (int i = 0; i < 10; i++)
            {
                wig.QueueWorkItem(
                    state => { Thread.Sleep(500); ++counter; return(null); }
                    );
            }

            Thread.Sleep(100);

            wig.Cancel(true);

            Assert.AreEqual(counter, 0);

            stp.Shutdown();
        }
示例#17
0
        private void TasksProducerThreadMain()
        {
            WorkItemCallback            workItemCallback            = new WorkItemCallback(this.SmartThreadMain);
            PostExecuteWorkItemCallback postExecuteWorkItemCallback = new PostExecuteWorkItemCallback(this.OneThreadDoneCallback);

            while (isProducerThreadRunning)
            {
                IWorkItemsGroup workItemsGroup = smartThreadPool;
                if (null == workItemsGroup)
                {
                    return;
                }

                try
                {
                    object data = this.curTaskGroup.OneTask_Produce();
                    if (data != null)
                    {
                        workItemCallback = new WorkItemCallback(this.SmartThreadMain);
                        workItemsGroup.QueueWorkItem(workItemCallback, data, postExecuteWorkItemCallback, CallToPostExecute.Always);
                        performance.tasksGenerated++;
                    }
                    else
                    {
                        GlobalVar.Instance.logger.Info("全部任务生产完毕.");
                        isProducerThreadRunning = false;
                    }
                }
                catch (ObjectDisposedException e)
                {
                    e.GetHashCode();
                    break;
                }
                Thread.Sleep(10);
            }
        }
示例#18
0
        private void StartThread_OnClick(object sender, RoutedEventArgs e)
        {
            STPStartInfo startInfo = new STPStartInfo()
            {
                MinWorkerThreads = 10,
                MaxWorkerThreads = 50,
                IdleTimeout      = 4 * 1000,
                EnableLocalPerformanceCounters = true
            };

            smart = new SmartThreadPool(startInfo);
            smart.Start();

            WorkItemCallback workItem   = this.DoWork;
            IWorkItemsGroup  itemsGroup = smart;

            for (int i = 1000; i < 56500; i++)
            {
                itemsGroup.QueueWorkItem(workItem, i, WorkItemPriority.Normal);
            }

            //sThread = new Thread(this.Mytask){IsBackground = true};
            //  sThread.Start();
        }
示例#19
0
        public void ActionT0()
        {
            IWorkItemResult wir = _wig.QueueWorkItem(Action0);

            Assert.IsNull(wir.State);
        }
        public Networking(Core core, TcpClient tcpClient)
        {
            Core      = core;
            TcpClient = tcpClient;

            Reader = new StreamReader(tcpClient.GetStream());
            Writer = new StreamWriter(tcpClient.GetStream())
            {
                AutoFlush = true
            };

            IsActive = true;

            Thread.Add(() =>
            {
                int errorCount = 0;

                do
                {
                    try
                    {
                        if (tcpClient.Available > -1)
                        {
                            string packageString = Reader.ReadLine();

                            if (!string.IsNullOrWhiteSpace(packageString))
                            {
                                ThreadPool.QueueWorkItem(() =>
                                {
                                    Core.Logger.Debug($"Receive: {packageString}", this);
                                    Package.Package package = new Package.Package(Core, packageString, this);

                                    if (package.IsValid)
                                    {
                                        package.Handle();
                                    }
                                });

                                errorCount = 0;
                            }
                            else
                            {
                                errorCount++;

                                if (errorCount > 10)
                                {
                                    Dispose();
                                }
                            }
                        }
                        else
                        {
                            Dispose();
                        }
                    }
                    catch (ThreadAbortException) { return; }
                    catch (Exception)
                    {
                        if (IsActive)
                        {
                            Dispose();
                        }
                    }
                } while (IsActive);
            });
        }
示例#21
0
 public static IWorkItemResult add(IWorkItemsGroup workItemsGroup, WorkItemCallback callback, Hashtable param, WorkItemPriority priority)
 {
     return(workItemsGroup.QueueWorkItem(callback, param, priority));
 }
示例#22
0
文件: Form1.cs 项目: mlabs-pl/stp
 private void EnqueueWorkItems(ref int startIndex, int count, string text, Color color, WorkItemPriority priority, IWorkItemsGroup wig, int sleepDuration)
 {
     for (int i = 0; i < count; ++i, ++startIndex)
     {
         wig.QueueWorkItem(
             DoNothing,
             new WorkItemState(new QueueUsageControl.QueueUsageEntry(string.Format("{0}{1} ({2})", text, startIndex, priority.ToString().Substring(0,2 )), color), sleepDuration),
             priority);
     }
     _workItemsGenerated += count;
 }
示例#23
0
 /// <summary>
 /// 后台业务处理推送统一调用接口
 /// 未持久化,可能出现丢失
 /// </summary>
 /// <param name="func">委托方法</param>
 /// <param name="workItemPriority">任务等级,默认的是正常</param>
 public void Push(Amib.Threading.Action func, WorkItemPriority workItemPriority = WorkItemPriority.Normal)
 {
     _workItemsGroup.QueueWorkItem(func, workItemPriority);
 }
        private void ThreadStartListening()
        {
            try
            {
                Core.Logger.Log($"Connecting to the specified server... Please wait.", Logger.LogTypes.Info);

                Client = new TcpClient();

                if (!Client.ConnectAsync(IPAddress, Port).Wait(5000))
                {
                    Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                    return;
                }

                Reader = new StreamReader(Client.GetStream());
                Writer = new StreamWriter(Client.GetStream());

                SentToServer(new Package(Package.PackageTypes.Authentication, new List <string> {
                    Password.Md5HashGenerator(), Password.SHA1HashGenerator(), Password.SHA256HashGenerator()
                }, null));

                string ReturnMessage = Reader.ReadLine();

                if (string.IsNullOrEmpty(ReturnMessage))
                {
                    Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                    return;
                }
                else
                {
                    Package Package = new Package(ReturnMessage, Client);
                    if (Package.IsValid)
                    {
                        Core.Logger.Log($"Receive: {Package.ToString()}", Logger.LogTypes.Debug, Client);

                        if (Package.DataItems[0] == Package.AuthenticationStatus.AccessGranted.ToString())
                        {
                            Core.Logger.Log($"You are now connected to the server.", Logger.LogTypes.Info);
                            IsActive = true;
                        }
                        else if (Package.DataItems[0] == Package.AuthenticationStatus.AccessDenied.ToString())
                        {
                            Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                            return;
                        }
                    }
                    else
                    {
                        Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                ex.CatchError();
                Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                return;
            }

            Thread Thread2 = new Thread(new ThreadStart(ThreadStartPinging))
            {
                IsBackground = true
            };

            Thread2.Start();
            ThreadCollection.Add(Thread2);

            do
            {
                try
                {
                    ThreadPool.QueueWorkItem(new WorkItemCallback(ThreadPreHandlePackage), Reader.ReadLine());
                }
                catch (Exception) { }
            } while (IsActive);
        }
示例#25
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;
            }
        }
示例#26
0
 public void BeginSendKeepAlive(NodeBind source, NodeBind dest, RouteContCallback cb)
 {
     wgKeepAlive.QueueWorkItem(new WorkItemCallback(BeginSendKeepAlive_tt),
                               new object[] { source, dest, cb }, WorkItemPriority.Highest);
 }
        //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);
        }
        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);
            }
        }
示例#29
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();
            }
        }
 /// <summary>
 /// Sent To Server
 /// </summary>
 /// <param name="p">Package to send.</param>
 public void SentToServer(Package p)
 {
     ThreadPool3.QueueWorkItem(new WorkItemCallback(ThreadSentToServer), p);
 }
        private async void StartListening()
        {
            try
            {
                string publicAddress = await IPAddressHelper.GetPublicIPAsync();

                string privateAddress = await IPAddressHelper.GetPrivateIPAsync();

                if (string.IsNullOrEmpty(publicAddress) || string.IsNullOrEmpty(privateAddress))
                {
                    Core.Logger.Log("Network is not available.", "Warning");
                    Dispose();
                }
                else
                {
                    if (Core.Settings.Server.GameModes.OfflineMode)
                    {
                        Core.Logger.Log("Players with offline profile can join the server.");
                    }

                    Thread.Add(() =>
                    {
                        IsActive = true;

                        do
                        {
                            try
                            {
                                TcpClient client = Listener.AcceptTcpClient();

                                ThreadPool.QueueWorkItem(() =>
                                {
                                    if (client != null)
                                    {
                                        Core.TcpClientCollection.Add(client);
                                    }
                                });
                            }
                            catch (ThreadAbortException) { return; }
                            catch (Exception) { }
                        } while (IsActive);
                    });

                    if (CheckPortOpen(publicAddress))
                    {
                        Core.Logger.Log($"Server started. Players can join using the following address: {publicAddress}:{Core.Settings.Server.Port.ToString()} (Global), {privateAddress}:{Core.Settings.Server.Port.ToString()} (Local) and with the following GameMode: {Core.Settings.Server.GameModes.ToString()}.");

                        if (Core.Settings.Server.CheckPort)
                        {
                            StartPortCheck(publicAddress);
                        }
                    }
                    else
                    {
                        Core.Logger.Log($"The specific port {Core.Settings.Server.Port.ToString()} is not opened. External/Global IP will not accept new players.");
                        Core.Logger.Log($"Server started. Players can join using the following address: {privateAddress}:{Core.Settings.Server.Port.ToString()} (Local) and with the following GameMode: {Core.Settings.Server.GameModes.ToString()}.");
                    }
                }
            }
            catch (Exception)
            {
                Dispose();
            }
        }
        //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(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);
        }