开发者

BackgroundWorker.ReportProgress breaks out of method

开发者 https://www.devze.com 2023-03-31 07:44 出处:网络
It seems like wherever I call ReportProgress on my BackgroundWorker, the processing of that method stops so my work never finishes. Example:

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 debu开发者_运维百科g 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?


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


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));
        }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号