开发者

Update UI every 1 second using Timer in C#

I have the following code in my application:

Task.Factory.Sta开发者_Python百科rtNew( () =>
{
    progressReporter.ReportProgress(() =>
    {
        stopWatch.Start();
        lblStatus.Text = "We've begun!";
    });

    int c = 0;

    DateTime starttime = DateTime.Now;

    foreach (string file in fileList)
    {
        c++;
        csvCreator.createCSV(file);

        progressReporter.ReportProgress(() =>
        {
            //Estimated time remaining
            if (c % 100 == 0)
            {
                TimeSpan timespent = DateTime.Now - starttime;
                int secondsremaining = (int)(timespent.TotalSeconds / c * (total - c));
                TimeSpan t = TimeSpan.FromSeconds(secondsremaining);
                lblTimeRemaining.Text = string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
                t.Hours,
                t.Minutes,
                t.Seconds,
                t.Milliseconds);
            }

            //Progress bar                            
            int percentComplete = (c * 100 / total);
            if ((int)percentComplete <= progressBar.Maximum)
            {
                progressBar.Value = (int)percentComplete;
            }
        }

    });      
}

Right now, my code checks for every 100th iteration and updates the UI. I'd prefer to check every second instead to provide a better user experience.

Any ideas on how I would do this?


You can use a timer object


Instead of if (c%100==0) , lookup your stopWatch : Did it reach 1 sec? If yes-> update ui.

Of course, reset stopWatch after each UI update.

That said, be aware that updating UI requires that the message loop runs. If the UI thread in stuck in a file processing loop, you UI won't be updated correctly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜