我怎样才能多次向后台工作人员报告进展情况?

时间:2016-06-16 16:40:57

标签: c# .net winforms

我创建了一个小类

public class MyProgress
        {
            public string Report1 { get; set; }
            public string Report2 { get; set; }
        }

然后在一个方法中,我想实时报告每个文件名:

private void DirSearch(string root, string filesExtension,string textToSearch)
        {
            List<MyProgress> prog = new List<MyProgress>();
            string[] filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories);
            for (int i = 0; i < filePaths.Length; i++)
            {
                int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0;
                if (var == 1)
                {
                    string filename = filePaths[i];
                    prog.Add(new MyProgress { Report1 = filename });
                }
            }
            backgroundWorker1.ReportProgress(0, prog);
        }

不确定ReportProgress是否应该在prog.Add行后面的FOR循环或内部。

然后在progresschanged事件中

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    foreach (p in (e.UserState as List<MyProgress>))
    {
        Console.WriteLine("Progress for {0} is {1}", p.);
    }              
}

我在foreach中遇到错误我不确定变量'p'应该是什么类型

我试过了:

foreach (List<MyProgress> p in (e.UserState as List<MyProgress>))

但是得到错误:

错误8无法将类型'Search_Text_In_Files.Form1.MyProgress'转换为'System.Collections.Generic.List'

2 个答案:

答案 0 :(得分:2)

OP完全改变了问题 你不知道p应该是什么?
提示您枚举MyProgress列表

foreach (var p in (e.UserState as List<MyProgress>))

但是你传递了一个字符串

backgroundWorker1.ReportProgress(0, filename);

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    Console.WriteLine(e.UserState.ToString());           
}

这是做工作的典型签名 即使DirSearch是工作方法,你应该将BackgroundWorker传递给它恕我直言 你应该把你的结果作为.Result - prog

传递出来
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {   
        // Get the BackgroundWorker that raised this event.
        BackgroundWorker worker = sender as BackgroundWorker;

        // Assign the result of the computation
        // to the Result property of the DoWorkEventArgs
        // object. This is will be available to the 
        // RunWorkerCompleted eventhandler.
        e.Result = ComputeFibonacci((int)e.Argument, worker, e);
    }

答案 1 :(得分:0)

  

不确定ReportProgress是否应该在FOR循环之后或在prog

之后

您想要从正在执行工作的for循环内部报告进度。如果在一次调用ReportProgress中传递进度报告列表,则在处理结束时将仅调用一次backgroundWorker1_ProgressChanged。所有工作完成后,所有进度报告都可以立即生效。

您当前的代码会报告正在进行的进度,并尝试在完成所有操作后再次报告。您将不同的数据类型传递到同一进度报告处理程序stringList<MyProgress>

for (int i = 0; i < filePaths.Length; i++)
{
    int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0;
    if (var == 1)
    {
        string filename = filePaths[i];
        backgroundWorker1.ReportProgress(0, filename);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    Console.WriteLine("Progress for {0} is {1}", e.UserState);
}