public void Stop()
        {
            _stop = true;
            _writeTimer.Change(Timeout.Infinite, Timeout.Infinite);
            _writeTimer.Dispose();

            _writeBackPool.WaitForIdle(SHUTDOWN_WAIT_TIMEOUT);
        }
Exemple #2
0
        private void LocalTest(string host)
        {
            threadPool.WaitForIdle();
            var pingList = PingDataList.Select(u => u.Ip).Distinct();

            using (var ping = new Ping())
            {
                foreach (var pingIp in pingList.Where(u => u != "超时"))
                {
                    foreach (var pingData in PingDataList.Where(u => u.Ip == pingIp))
                    {
                        pingData.LocalAnswerTime = "loading...";
                        pingData.TcpIpResult     = "loading...";
                    }
                    var pingStatus = ping.Send(pingIp);
                    HttpHelper.TcpIpTest(pingIp, host, out var timeConsume, out var dSize);
                    PingDataList.Where(u => u.Ip == pingIp).ToList().ForEach(u =>
                    {
                        u.LocalAnswerTime = pingStatus.Status == IPStatus.Success ? pingStatus.RoundtripTime.ToString() : "超时";
                        u.TimeConsume     = timeConsume;
                        u.DSize           = dSize;
                    });
                }
            }
        }
Exemple #3
0
        public void StartSuspended()
        {
            STPStartInfo stpStartInfo = new STPStartInfo();

            stpStartInfo.StartSuspended = true;

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);

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

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

            stp.Start();

            Assert.IsTrue(stp.WaitForIdle(200));
        }
Exemple #4
0
        public void DoWork(object[] states)
        {
            STPStartInfo stp = new STPStartInfo();

            stp.DisposeOfStateObjects = true;
            stp.CallToPostExecute     = CallToPostExecute.Always;
            stp.ThreadPriority        = ThreadPriority.Highest;
            stp.UseCallerCallContext  = true;
            stp.MaxWorkerThreads      = 20;
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            smartThreadPool.MaxThreads = states.Length;
            smartThreadPool.MinThreads = 1;
            foreach (object state in states)
            {
                IWorkItemResult i = smartThreadPool.QueueWorkItem(new
                                                                  WorkItemCallback(this.DoSomeWork), state);
                Data.Add(i.Result.ToString());
            }

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

            smartThreadPool.Shutdown();
        }
Exemple #5
0
        public void CancelCancelledWorkItemAbort()
        {
            ManualResetEvent waitToStart = new ManualResetEvent(false);

            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemResult wir = stp.QueueWorkItem(
                state => { waitToStart.Set(); while (true)
                           {
                               Thread.Sleep(1000);
                           }
                           return(null); }
                );

            waitToStart.WaitOne();

            wir.Cancel(false);

            Assert.IsTrue(wir.IsCanceled);

            bool completed = stp.WaitForIdle(1000);

            Assert.IsFalse(completed);

            wir.Cancel(true);

            try
            {
                wir.GetResult();
            }
            finally
            {
                stp.Shutdown();
            }
        }
Exemple #6
0
        public void TimeoutInProgressWorkItemSoftWithAbortOnWorkItemCancel()
        {
            bool             abortFailed    = false;
            ManualResetEvent waitToStart    = new ManualResetEvent(false);
            ManualResetEvent waitToComplete = new ManualResetEvent(false);

            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemResult wir = stp.QueueWorkItem(
                new WorkItemInfo()
            {
                Timeout = 500
            },
                state =>
            {
                waitToStart.Set();
                Thread.Sleep(1000);
                SmartThreadPool.AbortOnWorkItemCancel();
                abortFailed = true;
                return(null);
            });

            waitToStart.WaitOne();

            stp.WaitForIdle();

            Assert.IsTrue(wir.IsCanceled);
            Assert.IsFalse(abortFailed);
            stp.Shutdown();
        }
Exemple #7
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            txtLogs.Clear();
            if (File.Exists(_proxyPath) == false)
            {
                return;
            }
            _proxies = new List <string>();
            var proxies = File.ReadLines(_proxyPath);

            foreach (var proxy in proxies)
            {
                _proxies.Add(proxy.Trim());
            }
            if (_proxies.Count == 0)
            {
                return;
            }
            _tokenSource = new CancellationTokenSource();
            _token       = _tokenSource.Token;
            Running(true);
            var listClientId = txtClientIDList.Text.Trim();
            var clients      = Regex.Split(listClientId, "\n", RegexOptions.Multiline);

            _threadPool = new SmartThreadPool()
            {
                Concurrency = 1, MaxThreads = 1, MinThreads = 1
            };
            var totalClient = 0;
            var timeout     = int.Parse(numTimeout.Text);
            var proxyType   = comboProxyType.Items[comboProxyType.SelectedIndex].ToString();

            foreach (var _ in clients)
            {
                var client = _.Trim();
                if (client.Length <= 0)
                {
                    continue;
                }
                _threadPool.QueueWorkItem(DoWork, client, int.Parse(numThreads.Text), timeout, proxyType);
                totalClient++;
            }
            lbTotalProxy.Text  = _proxies.Count.ToString();
            lbTotalClient.Text = totalClient.ToString();
            new Thread(() =>
            {
                _threadPool.Start();
                _threadPool.Join();
                _threadPool.WaitForIdle();
                _threadPool.Dispose();
                _tokenSource.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                Running(false);
            })
            {
                IsBackground = true
            }.Start();
        }
Exemple #8
0
        // Upload the difference in the chunkLists
        private void UploadChunkList(ref List <ChunkInfo> chunkList_toUpload, string filePath, string blobName)
        {
            // SmartThreadPool threadPool = new SmartThreadPool();
            //  threadPool.MaxThreads = MaxConcurrentUploadThreads;

            if (logger != null)
            {
                logger.Log("Start UploadChunkList Create and Queue Threads");
            }
            SmartThreadPool threadPool = new SmartThreadPool();

            threadPool.MaxThreads = MaxConcurrentUploadThreads;

            foreach (ChunkInfo chunk in chunkList_toUpload)
            {
                ChunkInfo       chunkToUpload = chunk;
                IWorkItemResult wir1          = threadPool.QueueWorkItem(new WorkItemCallback(this.UploadChunk_Worker), new Tuple <string, string, ChunkInfo>(filePath, blobName, chunkToUpload));
                //    UploadChunk(filePath, blobName, ref chunkToUpload);
            }
            threadPool.Start();
            threadPool.WaitForIdle();
            threadPool.Shutdown();
            if (logger != null)
            {
                logger.Log("End UploadChunkList Create and Queue Threads");
            }
        }
Exemple #9
0
        public void CancelInProgressWorkItemSoftWithIgnoreSample()
        {
            Assert.Throws <WorkItemCancelException>(() =>
            {
                ManualResetEvent waitToStart    = new ManualResetEvent(false);
                ManualResetEvent waitToComplete = new ManualResetEvent(false);

                SmartThreadPool stp = new SmartThreadPool();
                IWorkItemResult wir = stp.QueueWorkItem(
                    state =>
                {
                    waitToStart.Set();
                    Thread.Sleep(100);
                    waitToComplete.WaitOne();
                    return(null);
                }
                    );

                waitToStart.WaitOne();

                wir.Cancel(false);

                waitToComplete.Set();

                stp.WaitForIdle();

                // Throws WorkItemCancelException
                wir.GetResult();

                stp.Shutdown();
            });
        }
Exemple #10
0
        public void DisposeCallerState()
        {
            STPStartInfo stpStartInfo = new STPStartInfo();

            stpStartInfo.DisposeOfStateObjects = true;

            SmartThreadPool smartThreadPool = new SmartThreadPool(stpStartInfo);

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

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

            IWorkItemResult wir2 =
                smartThreadPool.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.
            smartThreadPool.WaitForIdle();

            Assert.AreEqual(2, disposableCallerState.Value);

            smartThreadPool.Shutdown();
        }
Exemple #11
0
        public void CancelInProgressWorkItemSoftWithAbortOnWorkItemCancel()
        {
            bool             abortFailed  = false;
            ManualResetEvent waitToStart  = new ManualResetEvent(false);
            ManualResetEvent waitToCancel = new ManualResetEvent(false);

            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemResult wir = stp.QueueWorkItem(
                state => {
                waitToStart.Set();
                waitToCancel.WaitOne();
                SmartThreadPool.AbortOnWorkItemCancel();
                abortFailed = true;
                return(null);
            });

            waitToStart.WaitOne();

            wir.Cancel(false);

            waitToCancel.Set();

            stp.WaitForIdle();

            Assert.IsTrue(wir.IsCanceled);
            Assert.IsFalse(abortFailed);

            stp.Shutdown();
        }
Exemple #12
0
        private void MainThreadCheck()
        {
            SmartThreadPool s = new SmartThreadPool();

            s.MaxThreads = Convert.ToInt32(numericUpDown1.Value);
            foreach (string login in logins)
            {
                try
                {
                    if (break2)
                    {
                        break;
                    }
                    s.QueueWorkItem(dummy => CheckAccount(login), new object());
                }
                catch { }
            }
            try
            {
                s.WaitForIdle();
                s.Shutdown();
            }

            catch { }
            button7.Enabled = true;
            MessageBox.Show("CompleteD");
        }
        private object DoWaitForIdle(object state)
        {
            SmartThreadPool smartThreadPool = state as SmartThreadPool;

            smartThreadPool.WaitForIdle();
            return(null);
        }
Exemple #14
0
        public void CancelInProgressWorkItemSoftWithSample()
        {
            bool             cancelled      = false;
            ManualResetEvent waitToStart    = new ManualResetEvent(false);
            ManualResetEvent waitToComplete = new ManualResetEvent(false);

            SmartThreadPool stp = new SmartThreadPool();
            IWorkItemResult wir = stp.QueueWorkItem(
                state => {
                waitToStart.Set();
                waitToComplete.WaitOne();
                cancelled = SmartThreadPool.IsWorkItemCanceled;
                return(null);
            }
                );

            waitToStart.WaitOne();

            wir.Cancel(false);

            waitToComplete.Set();

            stp.WaitForIdle();

            Assert.IsTrue(cancelled);

            stp.Shutdown();
        }
Exemple #15
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");
        }
Exemple #16
0
        //copied from ThreadPool solution
        public void WaitForIdle()
        {
            ManualResetEvent isRunning = new ManualResetEvent(false);

            for (int i = 0; i < MaxWorkerThreads + 1; ++i)
            {
                _threadPool.QueueWorkItem(delegate { isRunning.WaitOne(); });
            }

            bool success = !_threadPool.WaitForIdle(1000);

            isRunning.Set();

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

            Assert.IsTrue(success);
        }
        public void GoodCallback()
        {
            SmartThreadPool stp = new SmartThreadPool();

            stp.QueueWorkItem(new WorkItemCallback(DoWork));

            stp.WaitForIdle();

            stp.Shutdown();
        }
        public void Stop()
        {
            _threadPool.WaitForIdle(SHUTDOWN_WAIT_TIMEOUT);
            _threadPool.Shutdown();

            if (_diskWriteBack != null)
            {
                _diskWriteBack.Stop();
            }
        }
Exemple #19
0
        // Entry-point for processing messages
        public virtual void ProcessArrivalMessages()
        {
            try
            {
                // Getting all necessary info and initialization stores before processing
                var validationSettings = GetValidationSettingsForProducts(checkingProductIds);
                var validationRules    = GetValidationRules();

                SetRulesForSettings(validationSettings, validationRules);

                lock (locker)
                {
                    messagesStore = new MessagesStore();

                    var messages = _arrivalMessagesRepository.GetNotProcessedMessages(checkingProductIds, null)
                                   .OrderBy(t => t.CreatedOn).ToList();

                    messagesStore.Messages = messages;

                    InitDictionary(messages);
                }

                SmartThreadPool smartThreadPool = new SmartThreadPool();

                // Max count threads, which can work together in one time
                var threadpoolMaxCountOfThreads = int.Parse(ConfigurationManager.AppSettings[SchedulerConfig.NumberOfSimultaneouslyProcessedMessagesAlias]);
                smartThreadPool.MaxThreads = (int)Math.Min(threadpoolMaxCountOfThreads, messagesStore.Messages.Count);

                // Parallel processing by using SmartThreadPool
                foreach (ArrivalMessage message in messagesStore.Messages)
                {
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.callback), new ThreadInfo
                    {
                        Message            = message,
                        ValidationSettings = validationSettings.Where(x => x.ProductId == message.ProductId).ToList(),
                    });
                }

                smartThreadPool.WaitForIdle();

                smartThreadPool.Shutdown();

                // Then we delete all files, if their count more than limit(another way it can call OutOfMemoryException)
                foreach (var checkingProductId in checkingProductIds)
                {
                    _downloadService.CheckTmpFilesDir(checkingProductId);
                }
            }
            catch (Exception er)
            {
                var errorMessage = GetExceptionInfo(er);

                _log.Error(errorMessage);
            }
        }
        public void ExceptionType()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            var workItemResult = smartThreadPool.QueueWorkItem(new Func <int>(ExceptionMethod));

            smartThreadPool.WaitForIdle();

            Assert.IsInstanceOf <System.NotImplementedException>(workItemResult.Exception);

            smartThreadPool.Shutdown();
        }
Exemple #21
0
        /// <summary>
        /// Starts the tasks execution.
        /// </summary>
        /// <returns>If has reach the timeout false, otherwise true.</returns>
        public override bool Start()
        {
            base.Start();
            m_threadPool = new SmartThreadPool();

            try
            {
                m_threadPool.MinThreads = MinThreads;
                m_threadPool.MaxThreads = MaxThreads;
                var workItemResults = new IWorkItemResult[Tasks.Count];

                for (int i = 0; i < Tasks.Count; i++)
                {
                    var t = Tasks[i];
                    workItemResults[i] = m_threadPool.QueueWorkItem(new WorkItemCallback(Run), t);
                }

                m_threadPool.Start();

                // Timeout was reach?
                if (!m_threadPool.WaitForIdle(Timeout.TotalMilliseconds > int.MaxValue ? int.MaxValue : Convert.ToInt32(Timeout.TotalMilliseconds)))
                {
                    if (m_threadPool.IsShuttingdown)
                    {
                        return(true);
                    }
                    else
                    {
                        m_threadPool.Cancel(true);
                        return(false);
                    }
                }

                foreach (var wi in workItemResults)
                {
                    Exception ex;
                    wi.GetResult(out ex);

                    if (ex != null)
                    {
                        throw ex;
                    }
                }

                return(true);
            }
            finally
            {
                m_threadPool.Shutdown(true, 1000);
                m_threadPool.Dispose();
                IsRunning = false;
            }
        }
        public void WaitForIdle()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(10 * 1000, 25, 0);

            ManualResetEvent isRunning = new ManualResetEvent(false);

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

            bool success = !smartThreadPool.WaitForIdle(1000);

            isRunning.Set();

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

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
        public void GoodPostExecute()
        {
            SmartThreadPool stp = new SmartThreadPool();

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

            stp.WaitForIdle();

            stp.Shutdown();
        }
        public static void RunThreads(Action <byte[], byte[], int> function, List <byte[]> arrayList, byte[] arrayRgbColorBytes, int threadsAmount)
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(60 * 1000, threadsAmount, threadsAmount);


            foreach (var byteArray in arrayList)
            {
                smartThreadPool.QueueWorkItem(function, byteArray, arrayRgbColorBytes, byteArray.Length);
            }

            smartThreadPool.Start();
            smartThreadPool.WaitForIdle();
            smartThreadPool.Shutdown();
        }
        private void LocalPing()
        {
            threadPool.WaitForIdle();
            var pingList = PingDataList.Select(u => u.Ip).Distinct();

            using (var ping = new Ping())
            {
                foreach (var pingIp in pingList.Where(u => u != "超时"))
                {
                    var pingStatus = ping.Send(pingIp);
                    PingDataList.Where(u => u.Ip == pingIp).ToList().ForEach(u => u.LocalAnswerTime = pingStatus.Status == IPStatus.Success ? pingStatus.RoundtripTime.ToString() : "超时");
                }
            }
        }
        public void ChainedDelegatesCallback()
        {
            SmartThreadPool stp = new SmartThreadPool();

            WorkItemCallback workItemCallback = new WorkItemCallback(DoWork);

            workItemCallback += new WorkItemCallback(DoWork);

            stp.QueueWorkItem(workItemCallback);

            stp.WaitForIdle();

            stp.Shutdown();
        }
Exemple #27
0
        public void DoWork(object [] states)
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

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

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

            smartThreadPool.Shutdown();
        }
Exemple #28
0
        private static void CheckApartmentState(ApartmentState requestApartmentState)
        {
            STPStartInfo stpStartInfo = new STPStartInfo();

            stpStartInfo.ApartmentState = requestApartmentState;

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);

            IWorkItemResult <ApartmentState> wir = stp.QueueWorkItem(() => GetCurrentThreadApartmentState());

            ApartmentState resultApartmentState = wir.GetResult();

            stp.WaitForIdle();

            Assert.AreEqual(requestApartmentState, resultApartmentState);
        }
        public void ChainedDelegatesPostExecute()
        {
            Assert.Throws <NotSupportedException> (() =>
            {
                SmartThreadPool stp = new SmartThreadPool();

                PostExecuteWorkItemCallback postExecuteWorkItemCallback = DoPostExecute;
                postExecuteWorkItemCallback += DoPostExecute;

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

                stp.WaitForIdle();

                stp.Shutdown();
            });
        }
        public void ChainedDelegatesCallback()
        {
            Assert.Throws <NotSupportedException> (() =>
            {
                SmartThreadPool stp = new SmartThreadPool();

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

                stp.QueueWorkItem(workItemCallback);

                stp.WaitForIdle();

                stp.Shutdown();
            });
        }