后台工作程序未返回值

时间:2017-09-08 13:59:01

标签: c# backgroundworker

我无法找到下面代码中的错误。由于Parallel.For正在冻结表单,我使用了一个后台工作者。但是,它不会返回字符串 如预期。此外,我不确定如何在backgroundworker中使用report for progressbar。我认为我不需要变量int i;但没有它,我无法报告进展情况。

private string trdoc(string str)
        {
            string alltrdoc;
            var alldoc = str.Split('\n');
            string[] alltrdoc1 = new string[alldoc.Length];
            pb1.Maximum = alldoc.Length;//progressbar
            pb1.Value = 0;

            int i = 0;

            BackgroundWorker bw = new BackgroundWorker();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(
            delegate (object o, DoWorkEventArgs e)
            {

                Parallel.For(0, alldoc.Length, new ParallelOptions { MaxDegreeOfParallelism = 4 },
                index =>
                {
                   alltrdoc1[index] = translate(alldoc[index]);

           bw.ReportProgress(i++);
                });

                e.Result = alltrdoc1;

            });

            bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate (object o, ProgressChangedEventArgs e)
        {

            if (pb1.Value <= pb1.Maximum)
            {
                pb1.Value++;
            }
        });

            // what to do when worker completes its task (notify the user)
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
            delegate (object o, RunWorkerCompletedEventArgs e)
            {
                alltrdoc1 = e.Result as string[];
            });

            bw.RunWorkerAsync();
            alltrdoc = string.Join(Environment.NewLine, alltrdoc1);
            saveposcdic();
            return alltrdoc;

        }

1 个答案:

答案 0 :(得分:0)

trdoc()方法的结束是当前实现中的问题所在:

bw.RunWorkerAsync();
alltrdoc = string.Join(Environment.NewLine, alltrdoc1);
saveposcdic();
return alltrdoc;

bw.RunWorkerAsync立即返回,因此alltrdoc将是一个空字符串。只有RunWorkerCompleted执行后,才会完全填充alltrdoc1数组。在那里你将创建alltrdoc并继续。