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();
        } 
        private static int calculateLabel(Individual[] weights)
        {
            Individual[] reversedWeights = { weights[1], weights[0] };
            weights[1].ResetScores();
            weights[0].ResetScores();
            SmartThreadPool smtp = new SmartThreadPool();
            for (int index = 0; index < numberOfGames; index++)
            {

                if (index % 2 == 1)
                {
                    smtp.QueueWorkItem(new WorkItemCallback(threadProc), weights);
                }
                else
                {
                    smtp.QueueWorkItem(new WorkItemCallback(threadProc), reversedWeights);
                }

            }
            smtp.WaitForIdle();
            smtp.Shutdown();
            //double strengthRatio = ((double)weights[0].Wins + (double)weights[0].Draws / 2) / numberOfGames;
            //return strengthRatio > 0.5 ? 1 : -1;
            return weights[0].Wins + 1/2 * weights[0].Draws;
        }
示例#3
0
        public void WorkItemWaitCanceling()
        {
            Assert.Throws<WorkItemTimeoutException>(() =>
            {
                SmartThreadPool smartThreadPool = new SmartThreadPool();

                ManualResetEvent cancelWaitHandle = new ManualResetEvent(false);

                // Queue a work item that will occupy the thread in the pool
                IWorkItemResult wir1 =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoSomeWork), null);

                // Queue another work item that will wait for the first to complete
                IWorkItemResult wir2 =
                    smartThreadPool.QueueWorkItem(new WorkItemCallback(this.SignalCancel), cancelWaitHandle);

                try
                {
                    wir1.GetResult(System.Threading.Timeout.Infinite, true, cancelWaitHandle);
                }
                finally
                {
                    smartThreadPool.Shutdown();
                }
            });
        }
 public void Migrate15Minute(SmartThreadPool tp)
 {
     tp.QueueWorkItem(() =>
     {
         GameSessionUserStats15MinuteMigrate();
     });
     tp.QueueWorkItem(() =>
     {
         GameUserActivity15MinuteMigrate();
     });
 }
 public void Migrate1Hour(SmartThreadPool tp)
 {
     tp.QueueWorkItem(() =>
     {
         GameSessionUserStats60Migrate();
     });
     tp.QueueWorkItem(() =>
     {
         GameUserActivity60Migrate();
     });
 }
        public void ExceptionReturning()
        {
            bool success = true;

            SmartThreadPool _smartThreadPool = new SmartThreadPool();

            DivArgs divArgs = new DivArgs();
            divArgs.x = 10;
            divArgs.y = 0;

            IWorkItemResult wir =
                _smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoDiv), divArgs);

            Exception e = null;
            try
            {
                wir.GetResult(out e);
            }
            catch (Exception ex)
            {
                ex.GetHashCode();
                success = false;
            }

            Assert.IsTrue(success);
            Assert.IsTrue(e is DivideByZeroException);
        }
        public void TimeoutInProgressWorkItemWithSample()
        {
            bool timedout = 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);
                    timedout = SmartThreadPool.IsWorkItemCanceled;
                    waitToComplete.Set();
                    return null;
                });

            waitToStart.WaitOne();

            waitToComplete.WaitOne();

            Assert.IsTrue(timedout);

            stp.Shutdown();
        }
        public static void getImagesAsync(List<FilmData> tempFilmList)
        {
            if (isNetworkAvailable())
            {

                SmartThreadPool smartThreadPool = new SmartThreadPool(
                                                                        15 * 1000,   // Idle timeout in milliseconds
                                                                        25,         // Threads upper limit
                                                                        1);         // Threads lower limit
                var bw = new System.ComponentModel.BackgroundWorker();
                bw.DoWork += (s, args) =>
                {
                    foreach (FilmData item in tempFilmList)
                    {
                        if (IsolatedStorageHelper.isFileAlreadySaved(item.imageUrl))
                            ImageHelper.addDownloadedItemsToFilmCollection(item.imageUrl);
                        else
                            smartThreadPool.QueueWorkItem(() => getImageFromUrl(item.imageUrl));
                    }

                    smartThreadPool.WaitForIdle(); // Wait for the completion of all work items
                };
                bw.RunWorkerAsync();
            }
        }
        public void ExceptionThrowing()
        {
            SmartThreadPool _smartThreadPool = new SmartThreadPool();

            DivArgs divArgs = new DivArgs();
            divArgs.x = 10;
            divArgs.y = 0;

            IWorkItemResult wir =
                _smartThreadPool.QueueWorkItem(new WorkItemCallback(this.DoDiv), divArgs);

            try
            {
                wir.GetResult();
            }
            catch(WorkItemResultException wire)
            {
                Assert.IsTrue(wire.InnerException is DivideByZeroException);
                return;
            }
            catch(Exception e)
            {
                e.GetHashCode();
                Assert.Fail();
            }
            Assert.Fail();
        }
        public void WaitAllT()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            bool success = true;

            IWorkItemResult<int>[] wirs = new IWorkItemResult<int>[5];

            for (int i = 0; i < wirs.Length; ++i)
            {
                wirs[i] = smartThreadPool.QueueWorkItem(new Func<int, int, int>(System.Math.Min), i, i + 1);
            }

            SmartThreadPool.WaitAll(wirs);

            for (int i = 0; i < wirs.Length; ++i)
            {
                if (!wirs[i].IsCompleted)
                {
                    success = false;
                    break;
                }

                int result = wirs[i].GetResult();
                if (i != result)
                {
                    success = false;
                    break;
                }
            }

            smartThreadPool.Shutdown();

            Assert.IsTrue(success);
        }
		public void WaitAny() 
		{ 
			SmartThreadPool smartThreadPool = new SmartThreadPool();

			bool success = false;

			IWorkItemResult [] wirs = new IWorkItemResult[5];

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

			int index = SmartThreadPool.WaitAny(wirs);

			if (wirs[index].IsCompleted)
			{
				int result = (int)wirs[index].GetResult();
				if (1 == result)
				{
					success = true;
				}
			}

			smartThreadPool.Shutdown();

			Assert.IsTrue(success);
		} 
		public void DoWork() 
		{ 
			SmartThreadPool smartThreadPool = new SmartThreadPool();

			DivArgs divArgs = new DivArgs();
			divArgs.x = 10;
			divArgs.y = 0;

			IWorkItemResult wir = 
				smartThreadPool.QueueWorkItem(new 
					WorkItemCallback(this.DoDiv), divArgs);

			Exception e;
			object obj = wir.GetResult(out e);
			// e contains the expetion that DoDiv threw
			if(null == e)
			{
				int result = (int)obj;
			}
			else
			{
				// Do something with the exception
			}

			smartThreadPool.Shutdown();
		} 
        public void TestMaxThreadsChange()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool(1 * 1000, 1, 0);

            for (int i = 0; i < 100; ++i)
            {
                smartThreadPool.QueueWorkItem(
                    new WorkItemCallback(this.DoSomeWork),
                    null);
            }

            bool success = WaitForMaxThreadsValue(smartThreadPool, 1, 1 * 1000);
            Assert.IsTrue(success);

            smartThreadPool.MaxThreads = 5;
            success = WaitForMaxThreadsValue(smartThreadPool, 5, 2 * 1000);
            Assert.IsTrue(success);

            smartThreadPool.MaxThreads = 25;
            success = WaitForMaxThreadsValue(smartThreadPool, 25, 4 * 1000);
            Assert.IsTrue(success);

            smartThreadPool.MaxThreads = 10;
            success = WaitForMaxThreadsValue(smartThreadPool, 10, 10 * 1000);
            Assert.IsTrue(success);

            smartThreadPool.Shutdown();
        }
        public static void Main()
        {
            SmartThreadPool stp = new SmartThreadPool();
            stp.OnThreadInitialization += OnInitialization;
            stp.OnThreadTermination += OnTermination;

            stp.QueueWorkItem(DoSomeWork);
        }
        public void GoodCallback()
        {
            SmartThreadPool stp = new SmartThreadPool();

            stp.QueueWorkItem(new WorkItemCallback(DoWork));

            stp.WaitForIdle();

            stp.Shutdown();
        }
        // Can't run this test, StackOverflowException crashes the application and can't be catched and ignored
        //[Test]
        public void NotTestThreadsMaxStackSize()
        {
            STPStartInfo stpStartInfo = new STPStartInfo()
            {
                MaxStackSize = 64 * 1024,
            };

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);
            stp.Start();

            IWorkItemResult<bool> wir = stp.QueueWorkItem(() => AllocateBufferOnStack(10 * 1024));

            bool result = wir.GetResult();
            Assert.IsTrue(result);

            wir = stp.QueueWorkItem(() => AllocateBufferOnStack(1000 * 1024));

            result = wir.GetResult();
            Assert.IsFalse(result);
        }
        private void CheckSinglePriority(ThreadPriority threadPriority)
        {
            STPStartInfo stpStartInfo = new STPStartInfo();
            stpStartInfo.ThreadPriority = threadPriority;

            SmartThreadPool stp = new SmartThreadPool(stpStartInfo);

            IWorkItemResult wir = stp.QueueWorkItem(new WorkItemCallback(GetThreadPriority));
            ThreadPriority currentThreadPriority = (ThreadPriority)wir.GetResult();

            Assert.AreEqual(threadPriority, currentThreadPriority);
        }
        /// <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 Character Parse(Character character, bool force)
        {
            stopwatch.Reset();
            Stopwatch watch = new Stopwatch();
            watch.Start();

            _current = character;

            // Only parse the character once a day unless forced
            if (character.LastParseDate.HasValue &&
                character.LastParseDate.Value.AddDays(7) > DateTime.Now && !force)
            {
                return character;
            }

            ParseCharacterInformation(character);

            //character.Achievements.Clear();

            string mainAchievementPageUrl = string.Format("http://{2}.battle.net/wow/en/character/{0}/{1}/achievement", character.Server, character.Name, character.Region);
            HtmlDocument doc = DownloadPage(mainAchievementPageUrl);
            List<AchievedAchievement> achievements = new List<AchievedAchievement>();

            ProcessPageForAchievements(doc.DocumentNode, character);
            pagesToParse = new List<HtmlDocument>();
            IList<string> extraPages = FindSubAchievementPages(doc.DocumentNode);

            SmartThreadPool pool = new SmartThreadPool();
            foreach (string pageUrl in extraPages)
            {
                pool.QueueWorkItem(new WorkItemCallback(ProcessPageOnNewThread), pageUrl);
            }

            pool.Start();
            pool.WaitForIdle();

            try
            {
                foreach (HtmlDocument page in pagesToParse)
                {
                    ProcessPageForAchievements(page.DocumentNode, character);
                }
            }
            catch (IndexOutOfRangeException)
            {
            }
            character.LastParseDate = DateTime.Now;
            character.CurrentPoints = character.TotalAchievementPoints;
            watch.Stop();

            return character;
        }
        public void QueueWorkItem_WhenMaxIsNull_Queues()
        {
            var info = new STPStartInfo
            {
                MaxQueueLength = null,
            };
            var pool = new SmartThreadPool(info);
            pool.Start();
            var workItem = pool.QueueWorkItem<object>(ReturnNull);

            // If rejected, an exception would have been thrown instead.
            Assert.IsTrue(workItem.GetResult() == null);
        }
        public void DoWork()
        {
            SmartThreadPool smartThreadPool = new SmartThreadPool();

            IWorkItemResult wir1 =
                smartThreadPool.QueueWorkItem(new
                WorkItemCallback(this.DoSomeWork1), null);

            IWorkItemResult wir2 =
                smartThreadPool.QueueWorkItem(new
                WorkItemCallback(this.DoSomeWork2), null);

            bool success = SmartThreadPool.WaitAll(new IWorkItemResult [] { wir1, wir2 });

            if (success)
            {
                int result1 = (int)wir1.Result;
                int result2 = (int)wir2.Result;
            }

            smartThreadPool.Shutdown();
        }
        public SerialCommunication_CSV()
        {
            LastValidFrame = DateTime.Now;
            _serialPort = new SerialPort();
            last_throughput_calculation = DateTime.Now;

            _smartThreadPool = SmartThreadPoolSingleton.GetInstance();
            //_smartThreadPool.Name = "ReceiveThreadedData";

            IWorkItemResult wir =
                        _smartThreadPool.QueueWorkItem(
                            new WorkItemCallback(this.ReceiveThreadedData), _serialPort);
        }
        public void GoodPostExecute()
        {
            SmartThreadPool stp = new SmartThreadPool();

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

            stp.WaitForIdle();

            stp.Shutdown();
        }
        public void ChainedDelegatesCallback()
        {
            SmartThreadPool stp = new SmartThreadPool();

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

            stp.QueueWorkItem(workItemCallback);

            stp.WaitForIdle();

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

			IWorkItemResult wir1 = 
				smartThreadPool.QueueWorkItem(new 
				WorkItemCallback(this.DoSomeWork1), null);

			IWorkItemResult wir2 = 
				smartThreadPool.QueueWorkItem(new 
				WorkItemCallback(this.DoSomeWork2), null);

			IWorkItemResult [] wirs = new IWorkItemResult [] { wir1, wir2 };

			int index = SmartThreadPool.WaitAny(wirs);

			if (index != WaitHandle.WaitTimeout)
			{
				int result = (int)wirs[index].Result;
			}

			smartThreadPool.Shutdown();
		} 
示例#26
0
                public ICancellable Run(Action action)
                {
                    if (_pool == null)
                    {
                        _pool = new Amib.Threading.SmartThreadPool(new Amib.Threading.STPStartInfo {
                            MaxWorkerThreads               = OptionNumberOfThreads,
                            AreThreadsBackground           = true,
                            EnableLocalPerformanceCounters = false,
                            WorkItemPriority               = Amib.Threading.WorkItemPriority.BelowNormal
                        });
                    }

                    return(new CancellableWrapper(_pool.QueueWorkItem(new Amib.Threading.Action(action))));
                }
        public void DoWork()
        {
            STPStartInfo stpStartInfo = new STPStartInfo();
            stpStartInfo.StartSuspended = true;

            SmartThreadPool smartThreadPool = new SmartThreadPool();

            smartThreadPool.QueueWorkItem(
                new WorkItemCallback(this.DoSomeWork),
                "Queued first",
                WorkItemPriority.BelowNormal);

            smartThreadPool.QueueWorkItem(
                new WorkItemCallback(this.DoSomeWork),
                "Queued second",
                WorkItemPriority.AboveNormal);

            smartThreadPool.Start();

            smartThreadPool.WaitForIdle();

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

            // Queue the work item
            IWorkItemResult<double> wir = smartThreadPool.QueueWorkItem(new Func<int[], double>(CalcAverage), numbers);

            // Do some other work here

            // Get the result of the operation
            double average = wir.Result;

            smartThreadPool.Shutdown();
        }
示例#29
0
        // Handle the processing of a request in here.
        private void ListenerCallback(IAsyncResult asyncResult)
        {
            var listener = asyncResult.AsyncState as HttpListener;
            HttpListenerContext context;

            if (listener == null)
            {
                return;
            }
            var isListening = listener.IsListening;

            try
            {
                if (!isListening)
                {
                    log.DebugFormat("Ignoring ListenerCallback() as HttpListener is no longer listening");
                    return;
                }
                // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
                // blocks until there is a request to be processed or some type of data is available.
                context = listener.EndGetContext(asyncResult);
            }
            catch (Exception ex)
            {
                // You will get an exception when httpListener.Stop() is called
                // because there will be a thread stopped waiting on the .EndGetContext()
                // method, and again, that is just the way most Begin/End asynchronous
                // methods of the .NET Framework work.
                string errMsg = ex + ": " + isListening;
                log.Warn(errMsg);
                return;
            }
            finally
            {
                // Once we know we have a request (or exception), we signal the other thread
                // so that it calls the BeginGetContext() (or possibly exits if we're not
                // listening any more) method to start handling the next incoming request
                // while we continue to process this request on a different thread.
                listenForNextRequest.Set();
            }

            if (Config.DebugMode && log.IsDebugEnabled)
            {
                log.Debug($"{context.Request.UserHostAddress} Request : {context.Request.RawUrl}");
            }

            OnBeginRequest(context);

            threadPoolManager.QueueWorkItem(ProcessRequestContext, context);
        }
        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));
        }
	    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 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();
		}