多线程并发,同时执行一个表,避免数据缺失


 FileSystemWatcher fileSystemWatcher1 = new FileSystemWatcher();//文件监控

 public static object locker = new object();

             ThreadPool.SetMinThreads(1, 1);//设置线程最小数量
   
            ThreadPool.SetMaxThreads(3, 1000);//设置线程最大数量和工作数量

 fileSystemWatcher1.Path = System.Configuration.ConfigurationManager.AppSettings["filePath"].ToString();//获取文件路径
            fileSystemWatcher1.Filter = "*.EFA";//设置获取文件的后缀名
            fileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
            fileSystemWatcher1.Changed += new FileSystemEventHandler(fileSystemWatcher1_Changed);  //当文件发生改变时执行    fileSystemWatcher1_Changed方法     
            fileSystemWatcher1.EnableRaisingEvents = true;



 private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {



                if (!listpath.Contains(e.FullPath))
                {


                    
                    
                    
                    
              
                        ThreadPool.QueueUserWorkItem(  Work, e.FullPath);将方法排入线程池中
                    
                   
                  
                }
               


            }
            catch { }
        }


    public void Work(object path)
        {
            try
            {
              
              Thread.Sleep(5000);
            

                    lock (locker)//添加互斥锁,保证数据完整性
                    {



                      对文件进行编辑和修改
                      







                       
                                


                            
                        }
                  
                    
                    
                
                
              
            }
            catch { }
        }


你可能感兴趣的:(多线程并发,同时执行一个表,避免数据缺失)