예제 #1
0
        //
        // this method runs in another thread,
        // picking off the next thread item to run off the queue
        // until manager tells us to stop
        //
        public void Run()
        {
            //Helper.MtWriteLine( "ThreadPoolThread [{0}] - entered run().", _ID ) ;

            while (true)
            {
                if (_tpm.IsShutdown)
                {
                    //Helper.MtWriteLine( "ThreadPoolThread [{0}] - shutdown - exited run().", _ID ) ;
                    break;                      // synced internally - quick exit if manager says enough is enough
                }

                using (MyThreadPoolItemBase tpi = _tpm.NextThreadPoolItem())                   // synced internally - get next item off the queue ;
                {
                    if (tpi == null)
                    {
                        ST.Thread.Sleep(100);                            // sleep 1/10 second - try again
                        continue;
                    }

                    //Helper.WriteLine( "ThreadPoolThread [{0}] - start run - item [{1}].", _ID, tpi.ID ) ;

                    try
                    {
                        tpi.Run();                          // found something to run -run thread pool item's code
                    }
                    catch (Exception ex)                    // cant let exceptions escape - or else thread will die
                    {
                        Helper.MtWriteLine("ThreadPoolThread [{0}], item [{1}] - EXCEPTION:\n\t{2}\n\t\t{3}",
                                           _ID, tpi.ID, ex.Message, ex.StackTrace);
                    }
                    tpi.IsFinished = true;                      // synced - this tpi now marked for deletion

                    //Helper.WriteLine( "ThreadPoolThread [{0}] - end	 run - item [{1}].", _ID, tpi.ID ) ;
                }
            }

            //Helper.MtWriteLine( "ThreadPoolThread [{0}] - exited run().", _ID ) ;
        }
예제 #2
0
        //
        // called from main thread
        //
        public void Queue(MyThreadPoolItemBase tpi)
        {
            if (this.IsShutdown)
            {
                Helper.MtWriteLine("Thread pool is shutting down. Can't queue new item [{0}] that will never be run, dude.", tpi.ID);
                return;
            }

            if (tpi.IsStarted)
            {
                throw new Exception("ThreadPoolItem #" + tpi.ID + " has already been started. Create a new one.");
            }

            this.ThrottleThreadPool();              // wait for thread count to be less than maximum unstarted + running queue length

            tpi.IsFinished        = false;
            tpi.ThreadPoolManager = this;

            lock ( _lock )
            {
                _tpiQueue.Add(tpi);
            }
        }