How to update the progress bar one step, each cycle of the cycle? WITH#

Creating a .net application in C #, Windows forms. How to update progress bar 1 step every cycle cycle cycle 100 cycle? (Im processing the excel sheet in a loop.) The execution controls are in the UI class, which connects to the controller class, which connects to the user class (MVC Template). The loop is in a custom class. Do I need to send an instance of the UI class to the end in each method, or is there a better way?

Currently, the progress bar is updated when the cycle ends. Application.doevents and .update or .refresh do not work.

+3
source share
3 answers

Say below that your class is responsible for doing work with the loop. Add an event to indicate your progress. Then, from your user interface, simply handle this event and update the progress bar accordingly.

sealed class Looper
{
    public event EventHandler ProgressUpdated;

    private int _progress;
    public int Progress
    {
        get { return _progress; }
        private set
        {
            _progress = value;
            OnProgressUpdated();
        }
    }

    public void DoLoop()
    {
        _progress = 0;
        for (int i = 0; i < 100; ++i)
        {
            Thread.Sleep(100);
            Progress = i;
        }
    }

    private void OnProgressUpdated()
    {
        EventHandler handler = ProgressUpdated;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

You can implement this by specifying BackgroundWorkeras part of your user interface where in the event backgroundWorker.DoWorkyou are calling looper.DoLoop(). Then in the event handler looper.ProgressUpdatedyou can call backgroundWorker.ReportProgressto increase your progress bar from the user interface thread.

, , , , ProgressUpdated ( EventArgs, : , , ).

, , . UI , ( 0 100, ).

, .

+5

, . UI โ†’ "UpdaterClass" โ†’ .

Updater . , Updater.StepProgressBar() - , . Updater , .

, . , .

psuedocode:

class Updater()
{

  public ProgressBar pb;

  delegate void UpdateProgressBar();

  public StepProgressBar()
  {
     if(pb.InvokeRequired)
     {
          BeginInvoke(new UpdateProgressBar(this.StepProgressBar);
     }
     else
     {
          pb.Step();
      }
   }

}

- .

+1

. , , . .

eg. (warning, psuedocode):

MyCustomClass class = new MyCustomClass();
class.ProgressUpdated += (s,e)=>{ /* update UI */};
class.StartLoop();
+1
source

Source: https://habr.com/ru/post/1765106/


All Articles