0

在顶部Form1我有:

int searchTime;
        public TimeSpan ts_timeElapsed;
        DirectoryInfo dirinf = new DirectoryInfo(@"C:\");
        List<FileSystemInfo> fsi = new List<FileSystemInfo>();
        List<string> texts = new List<string>();

        public Form1()
        {
            InitializeComponent();

            label6.Visible = false;
            searchTime = 0;
            label4.Visible = false;
        }

然后我有一个按钮单击它启动backgroundWorker

private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
            button1.Enabled = false;
            timer1.Enabled = true;
        }

然后backgroundWorker1_DoWork事件:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Search(".xml", dirinf, fsi);
            backgroundWorker1.ReportProgress(100);

        }

然后是Search功能代码:

public void Search(string strExtension,
                            DirectoryInfo di,
                            List<FileSystemInfo> pResult)
        {
            try
            {

                foreach (FileInfo fi in di.GetFiles())
                {
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action(() => label2.Text = fi.Name));
                    }
                    if (fi.Name == "MessageLog.xsl")
                    {
                        foreach (FileInfo fii in di.GetFiles())
                        {
                        if (fii.Extension == strExtension)
                            pResult.Add(fii);
                        }
                        if (InvokeRequired)
                        {
                            BeginInvoke(new Action(() => label4.Text = pResult.Count.ToString() + Environment.NewLine));
                        }

                    }
                }

                    foreach (DirectoryInfo diChild in di.GetDirectories())
                        Search(strExtension, diChild, pResult);

            }
            catch (Exception e)
            {
            }
        }

搜索从 开始c:\。程序在搜索大约 5 个文件后暂停几秒钟,然后继续搜索更多文件几秒钟,然后最终冻结。即使它与后台工作人员一起工作,我也无法点击任何内容。

然后几次后,它搜索快速流畅,没有暂停或冻结。

为什么前几次搜索暂停并冻结,但后续搜索顺利进行?

4

0 回答 0