线程,线程数控制!

多线程与线程池的介绍看这里
http://edobnet.cnblogs.com/archive/2005/11/29/287094.html

        //private int threadNum = 0;
        
//private AutoResetEvent myResetEvent = new AutoResetEvent(false);
        /// <summary>
        
/// 线程记数器
        
/// </summary>

        private int number = 0;

        
/// <summary>
        
/// 线程池执行
        
/// </summary>

        public void Execute()
        
{
            
int maxCount = int.Parse(ConfigurationSettings.AppSettings["Count"]);
            
int time = int.Parse(ConfigurationSettings.AppSettings["Time"]);
            
foreach (TG_EvaluteBaseDatasSet service in this)
            
{
                
                
                
//                System.Threading.ThreadStart ts = new System.Threading.ThreadStart(service.GetXMLResult);
                
//                System.Threading.Thread th = new System.Threading.Thread(ts);
                
//                th.Start();
                WaitCallback async = new WaitCallback(FExeute);

                
while(true)
                
{
                    
                    Monitor.Enter(number);
                    
if(number>maxCount)
                        Thread.Sleep(time);
                    
else
                        
break;
                    Monitor.Exit(number);
                }

                
if(ThreadPool.QueueUserWorkItem(async,service))
                    Interlocked.Increment(
ref number);
            }

            
while(true)
            
{
                
//myResetEvent.Set();
                Monitor.Enter(number);
                
if( number <= 0)
                    
break;
                
else
                    Thread.Sleep(time);
                Monitor.Exit(number);
            }

            OnTgFinishReport(
new EventArgs());

        }

        
/// <summary>
        
/// 线程执行一个计算
        
/// </summary>
        
/// <param name="Param">执行对象<see cref="GleNet.HG.HTResolver.TG_EvaluteBaseDatasSet">TG_EvaluteBaseDatasSet</see></param>

        public  void FExeute(object Param)
        
{
            
//myResetEvent.WaitOne();
            using(TG_EvaluteBaseDatasSet service = (TG_EvaluteBaseDatasSet)Param)
            
{
                service.doResult();
                writeFile(Path,service)    ;
                OnTgReport(
new ReportEvent(service.TE_PASS_RANGE,service.TE_YEAR,service.TE_MONTH,int.Parse(service.TE_I_E_FLAG),int.Parse(service.TE_ENTRY_TYPE),number));
            }

            Interlocked.Decrement(
ref number);
            Console.WriteLine(
"LEFT:"+number);
            
        }

由程序控制线程数量,并且, 由MONITOR进行保护!

posted on 2005-12-26 16:01  edobnet  阅读(3338)  评论(2编辑  收藏  举报