如何在某些条件下限制循环的循环次数?

时间:2014-01-29 09:56:20

标签: c# asp.net linq loops for-loop

我做了一个这样的循环:

    int total;
    total = ((toVal - fromVal) + 1) * 2;
    RadProgressContext progress = RadProgressContext.Current;
    progress.Speed = "N/A";

    finYear = fromVal;

    for (int i = 0; i < total; i++)
    {
          decimal ratio = (i * 100 / total);

            progress.PrimaryTotal = total;
            progress.PrimaryValue = total;
            progress.PrimaryPercent = 100;

            progress.SecondaryTotal = 100; // total;
            progress.SecondaryValue = ratio;//i ;
            progress.SecondaryPercent = ratio; //i;


            progress.CurrentOperationText = "Step " + i.ToString();
            if (!Response.IsClientConnected)
            {
                //Cancel button was clicked or the browser was closed, so stop processing
                break;
            }

            progress.TimeEstimated = (total - i) * 100;
            //Stall the current thread for 0.1 seconds
            System.Threading.Thread.Sleep(100);


    }

现在我希望根据toVal & fromVal运行特定方法 在前一个循环中但没有相同的循环数 我想在这样的循环中运行它:

   for (fromVal; fromVal < toVal  ; fromVal++)
    {
        PrepareNewEmployees(calcYear, fromVal);
    }

例如:

fromVal =  2014 
toVal   = 2015 

所以我想跑两次而不是4次!像这样:

PrepareNewEmployees(calcYear, 2014);
PrepareNewEmployees(calcYear, 2015);

但是在上一个循环for (int i = 0; i < total; i++)

2 个答案:

答案 0 :(得分:1)

您错过了进度条更新的重点。您不应该运行4次迭代并且每2次迭代执行一些工作,但是相反。做一个循环:

 for (int i = fromVal; i < toVal; i++)
{
    PrepareNewEmployees(...);
    decimal ratio = ((double)toVal-i)/(toVal-fromVal) *100;
    //Some other things, that need to be done twice in an iteration
}

答案 1 :(得分:0)

因为您已经使用Thread,所以请考虑实施以下内容:

public void ResetProgress()
{
    SetProgress(0);
}

public SetProgress(int percents)
{
    // set progress bar to a given percents/ratio
    // you will have to use Invoke and blablabla
}

然后任何您的作业将如下所示

ResetProgress();
// note: you need to remember from which value you start to be able to calculate progress
for (int i = startVal; i < toVal  ; i++)
{
    PrepareNewEmployees(calcYear, i);
    SetProgress(100 * (i - startVal) / (toVal - startVal)); // in percents [0-100]
}
// optional, required if you exit loop or use suggestion below
SetProgress(100);

您也可以对其进行优化,不要在每个步骤后更新进度,而是在执行一定数量的步骤之后。例如,不要调用SetProgress,而是执行

if(i % 10 == 0)
    SetProgress();

这会使SetProgress的次数减少十倍。当然,有一些假设,例如:i从0开始,如果你想在结尾处有100%的条形,那么i应该可以被10分割。只是一个想法开始。 / p>