0

我正在尝试制作一个程序,该程序使用 parallel.foreach 在特定目录及其子目录的文件中查找特定字符串,它在大约 90% 的迭代中工作正常,但之后程序挂起,并且不做任何事物。

private void searchParallel()
{
    directories.Clear();
    lbResults.Items.Clear();
    if (cbDirectory.Text.Length != 0)
    {
        getAllDirectories(cbDirectory.Text);

        pbSearchProgress.Maximum = directories.Count;
        pbSearchProgress.Minimum = 0;
        pbSearchProgress.Value = 0;
        //foreach (String dir in directories)
        ParallelOptions options = new ParallelOptions();
        options.MaxDegreeOfParallelism = 10;
        Parallel.ForEach(directories,options, (dir) =>
        {
            try
            {
                //MessageBox.Show(dir.ToString());
                String[] files = Directory.GetFiles(dir);

                foreach (String file in files)
                {
                    //MessageBox.Show(file.ToString());

                    if (checkFilePermission(file))
                    {
                        StreamReader reader = new StreamReader(file);
                        //MessageBox.Show(file);
                        int lineCount = 0;
                        while (reader.Peek() != -1)
                        {
                            Application.DoEvents();
                            String line = reader.ReadLine();
                            lineCount++;
                            if (line.ToLower().Contains(txtSearch.Text.ToLower()))
                            {
                                updateList(file, lineCount);
                            }
                            if (isSearching == false)
                            {


                            }
                        }
                    }
                    //if (isSearching == false)
                    //{
                    //    break;
                    //}
                }
                pbMakeProgress();
                //if (isSearching == false)
                //{
                //    loopState.Stop();
                //}
                //MessageBox.Show("Search Completed.");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

        });
    }
}
private void updateList(String file, int lineCount)
{
    if (lbResults.InvokeRequired)
    {
        listDelegate lstDelegate = new listDelegate(updateList);
        lbResults.Invoke(lstDelegate, new object[] { file, lineCount });

    }
    else
    {
        lbResults.Items.Add("Found in " + file + " at line: " + lineCount);
    }

}

private void pbMakeProgress()
{
    if (pbSearchProgress.InvokeRequired)
    {
        pbSearchProgress.Invoke(new MethodInvoker(pbMakeProgress));
    }
    else
    {
        pbSearchProgress.Value++;
    }
}

pbMakeProgress 更新进度条的值,updateList 更新列表框,getAllDirectories 获取子目录,directories 是包含要遍历的所有文件夹名称的列表。

4

0 回答 0