BackgroundWorker.ReportProgress 突破方法

发布于 2024-12-01 23:38:15 字数 595 浏览 1 评论 0原文

似乎无论我在BackgroundWorker 上调用ReportProgress,该方法的处理都会停止,因此我的工作永远不会完成。示例:

int numQuals = this.Model.Names.Count();
int currentQual = 0;
int fivePercent = (int)(numQuals * .05);
foreach (var qualName in this.Model.Names)
{
    if ((worker != null) && ((currentQual % fivePercent == 0)))
    {
        worker.ReportProgress((int) (((float)++currentQual / numQuals) * 100));
    }

    // This next line never processes. I can debug and it will 
    // break at the ReportProgress line but won't ever break here
    this.myContainer.Add(...
}

有谁知道这是为什么吗?

It seems like wherever I call ReportProgress on my BackgroundWorker, the processing of that method stops so my work never finishes. Example:

int numQuals = this.Model.Names.Count();
int currentQual = 0;
int fivePercent = (int)(numQuals * .05);
foreach (var qualName in this.Model.Names)
{
    if ((worker != null) && ((currentQual % fivePercent == 0)))
    {
        worker.ReportProgress((int) (((float)++currentQual / numQuals) * 100));
    }

    // This next line never processes. I can debug and it will 
    // break at the ReportProgress line but won't ever break here
    this.myContainer.Add(...
}

Does anyone have any idea why this is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

永言不败 2024-12-08 23:38:15

您是否设置了 worker.WorkerReportsProgress=true ?否则,后台工作程序将异常终止,并且工作将无法完成。

Have you set worker.WorkerReportsProgress=true ? Otherwise, the background worker will terminate with an exception and the work will not be fullfilled.

白况 2024-12-08 23:38:15

我建议将您的计算逻辑分离到不同的行。我讨厌从其他开发人员那里看到这样的内联内容。它更难阅读,更难调试(正如您的问题所指出的)。

如果你在 do work 方法中,你的worker 永远不应该为空。尽管我确实建议执行空值检查 - 如果此处存在空值,则其他内容会出现重大错误。

 if ((worker != null) && ((currentQual % fivePercent == 0)))
 {
        object result =  ((float)++currentQual / (float)numQuals) * 100;
        int resultint = 0;
        if(Int32.TryParse(result.ToString(), out resultint))
        {
            worker.ReportProgress(Convert.ToInt32(result));
        }
 }

I would recommend separating out your calculating logic to a different line. I hate seeing inline stuff like this from other developers. It's harder to read and harder to debug (as your question points out).

Your worker should never be null if you are inside the do work method. Although I do recommend performing null checks - if a null existed here something else is majorly wrong.

 if ((worker != null) && ((currentQual % fivePercent == 0)))
 {
        object result =  ((float)++currentQual / (float)numQuals) * 100;
        int resultint = 0;
        if(Int32.TryParse(result.ToString(), out resultint))
        {
            worker.ReportProgress(Convert.ToInt32(result));
        }
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文