日期:2014-05-18  浏览次数:21027 次

c#多线程查找文件问题
比如

 
C# code

Thread t = null;
            for (int i = 1; i <= 5; i++)
            {
                t = new Thread(searchthead);//searchthead为查找文件的方法 返回字符串数组
                
            t.Start();
            }



但这样用,会查找出5个同样的文件出来,怎样当一个线程查找过的文件,另一个线程就不去查了?

------解决方案--------------------
1:你的文件有多少?如果不是上W的话,无需使用多线程。
2:先建立一个文件List,根据算法把不同的序号区段分配给不同的线程。
比如:有1-10000个文件,那么分配
1-2000给线程1。
------解决方案--------------------
探讨
ZengHD ,我查找的是同一文件夹

------解决方案--------------------
多线程写起来比较复杂啊,我把代码贴到这里给你吧。不知道你能不能看明白;有点长,我使用它来搜索文件的注释狠详细
--------------------------frmSerach.cs---------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;

namespace MyUdisk
{
public partial class frmSerach : Form
{
private CThreadSearch m_objThreadC;
public static bool Initial_flag;
public static frmStart frmtmp;
int filecount;//记录搜索到文件的个数;
public frmSerach()
{
InitializeComponent();
m_objThreadC = new CThreadSearch(this, new SearchFileEventHandler(m_objThreadC_SearchEvent));
Initial_flag = false;
filecount = 0;
listViewFiles.DoubleClick += new EventHandler(listViewFiles_DoubleClick);
this.cmntrv_Path.TreeView.ImageList = this.imglist;

}

void listViewFiles_DoubleClick(object sender, EventArgs e)
{
if(listViewFiles.Items.Count>0)
{ Clipboard.Clear();
Clipboard.SetText(listViewFiles.Items[0].SubItems[3].Text.Trim());
if (MessageBox.Show("提示:你所选文件的完整路径已经复制到剪贴板上,\n关闭本窗体请点击是,重新选择请点击否", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{ this.Dispose();
} } }
 //事件处理函数
void m_objThreadC_SearchEvent(CThreadSearch sender, CSearchFileEventArgs args)
{
ProcessEvent(m_lblC, args);
}

//处理CThreadSearch对象传回来的事件对象
void ProcessEvent(Label lbl , CSearchFileEventArgs args)
{
switch (args.EventType)
{
case SearchFileEventTypes.Start:
lbl.Text = "查找线程启动...";
break;
case SearchFileEventTypes.Stop:
lbl.Text = "查找线程停止.";
break;
case SearchFileEventTypes.ProcessFile:
lbl.Text = "当前位置:"+args.FilePath;
break;
case SearchFileEventTypes.MatchedFile:
lbl.Text = "搜索到文件:"+args.FilePath;
//如果匹配则调用增加函 m_lstFiles.Items.Add(args.FilePath);
this.additemtolistview(args.FilePath);
filecount =filecount +1;
break;
case SearchFileEventTypes.Error:
lbl.Text = "错误:" + args.FilePath;
break;
}
}


private void additemtolistview(string filepath)
{


m_lbCount.Text =" 共搜索到"+ this.filecount.ToString