线程问题
我有个文件夹A 下面有很多文件夹 每个文件夹下面是不定时的放文件的我是想要用多线程查找不同文件夹下面的文件,一旦发现有文件,则将其上传至数据库中
这个通过bz的帮助我已经写好代码了,但是有问题出现了,就是在用多线程时,可能出线不同线程访问到了同个文件,
所以就报错:该文件正在被另一个线程使用,请先停止
我的问题是:这个该怎么解决啊?谢谢了!
private void ThreadsUpLoad() { DirectoryInfo di = new DirectoryInfo(folderPath); DirectoryInfo[] folderFiles = di.GetDirectories(); try { pPath = new string[folderFiles.Length]; for (int j = 0; j < pPath.Length; j++) { for (int i = 0; i <= j; i++) { string folderNode = folderFiles[i].FullName; pPath[j] = folderNode; } } threads = new Thread[pPath.Length]; for (int k = 0; k < threads.Length; k++) { threads[k] = new Thread(Run); threads[k].Name = pPath[k]; threads[k].Start(); //flock(threads[k]); } } catch (Exception Ex) { Console.WriteLine(Ex.Message); } } private void Run() { Run(Thread.CurrentThread.Name); } /// <summary> /// 监控文件夹下面的文件、只要有文件,则将其上传至数据表中,然后删除 /// </summary> /// <param name="pPath"></param> private void Run(string pPath) { SqlConnection mail_con = new SqlConnection("Server=192.168.1.146;Initial Catalog=EMail;uid=sa;pwd=Dhcs)_+"); mail_con.Open(); SqlCommand mail_cmd = mail_con.CreateCommand(); mail_cmd.Connection = mail_con; string mail_sql = string.Empty; string reciver = string.Empty; FileSystemWatcher fsw = new FileSystemWatcher(pPath); fsw.Filter = "*.*";//监控所有类型 DirectoryInfo directNode = new DirectoryInfo(pPath); FileInfo[] files = directNode.GetFiles(); for (int i = 0; i < files.Length; i++) { string folderNode = files[i].FullName; int index1 = folderNode.IndexOf('_') + 1; string resu = folderNode.Substring(index1, 6); reciver = resu + "@"; if (files[i] != null) { //将文件内容转换成二进制 FileStream fs = new FileStream(files[i].FullName, FileMode.Open); int fsLeng = Convert.ToInt32(fs.Length); Byte[] filebyteArray = new byte[fsLeng]; BinaryReader br = new BinaryReader(fs); for (int k = 0; k < fsLeng; k++) //循环数组大小那么多次 { //将数据读取出来放在数组中 br.Read(filebyteArray, 0, fsLeng); //第一个数组用0表示 } br.Close(); //关闭二进制流写入器 fs.Close(); //关闭文件流 try { string fileId = GetFileID(mail_con); //获取新的文件id mail_sql = @"Insert into MailRecive_Msg (FileID,StreamFile,Reciver) Values (@fileID,@streamFile,@reciver)"; //将文件存入到数据库表:ReciveInfo mail_ = mail_sql; mail_cmd.Parameters.Clear(); mail_cmd.Parameters.AddWithValue("@fileID", fileId); mail_cmd.Parameters.AddWithValue("@streamFile", filebyteArray); mail_cmd.Parameters.AddWithValue("@reciver", reciver); int mailNo = (int)mail_cmd.ExecuteNonQuery(); if (mailNo == 1) { files[i].Delete(); //上传到数据库成功后将其删除 } } catch { } } } mail_con.Close(); mail_con.Dispose(); fsw.EnableRaisingEvents = true;//开启监控请问各位我该如何加啊?加在哪里呢?