程序依赖并行性,Parallel.ForEach

时间:2013-01-09 20:45:27

标签: c# winforms parallel-processing task-parallel-library parallel.foreach

我正在尝试创建一个程序,使用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获取子目录, 目录是包含要遍历的所有文件夹的名称的列表。

0 个答案:

没有答案