此BackgroundWorker声明不报告进度

时间:2019-06-01 16:14:56

标签: winforms backgroundworker

我的错误在哪里?我认为一切都很好,但仍然看到此异常:

  

异常{“此BackgroundWorker声明未报告   进展。修改WorkerReportsProgress以声明它确实报告   进度。”}。引发了异常   _worker.ReportProgress((int)(progressPercentage * 100))。

有人可以推荐我一个具有丰富数据的ftp服务器以进行测试下载和上传吗?

这是我的代码:

    this._worker = new BackgroundWorker();

    this._worker.WorkerSupportsCancellation = true;
    this._worker.WorkerSupportsCancellation = true;

    this._worker.ProgressChanged += backgroundWorker1_ProgressChanged;
    this._worker.DoWork += backgroundWorker1_DoWork;

using (FileStream fs = new    FileStream(Path.Combine(this._ftpInfo.SaveDirectory, this._ftpInfo.FileName), FileMode.CreateNew, FileAccess.Write))
                    {


                byte[] buffer = new byte[1024];
                    int len;
                    int byteTotal = 0;

                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        await fs.WriteAsync(buffer, 0, len);
                        byteTotal += len;
                        double index = (double)(byteTotal);
                        double total = (double)buffer.Length;
                        double progressPercentage = (index / total);
                        _worker.ReportProgress((int)(progressPercentage*100));

                    }
                    fs.Close();

2 个答案:

答案 0 :(得分:0)

您两次有此行:

this._worker.WorkerSupportsCancellation = true;

其中一个可能应该是:

this._worker.WorkerReportsProgress = true;

在旁注中,考虑using Task.Run with IProgress<T> instead of BackgroundWorker。生成的代码将更短,并且类型安全性更高。

答案 1 :(得分:-1)

您必须通过对象属性将WorkerReportsProgress设置为True