Say the below is your class responsible for doing the work with the loop in it. Add an event to indicate your progress. Then from your UI simply handle that 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 might implement this by having a BackgroundWorker
as part of your UI, where in the backgroundWorker.DoWork
event you call looper.DoLoop()
. Then in your handler for the looper.ProgressUpdated
event you can call backgroundWorker.ReportProgress
to increment your progress bar from the UI thread.
Note that it would probably make more sense to include the progress itself in the information carried by your ProgressUpdated
event (I just didn't feel like writing out a new class deriving from EventArgs
to illustrate this; you probably get the picture anyway).
Also note that the above really doesn't make sense unless you're executing your code with the loop on a separate thread from the UI thread. Otherwise, all of your work is getting done before the next UI refresh anyway, so your progress bar would not be providing any value (it would just go from 0 to 100 when the loop completed).
Just an example of how this sort of thing can be achieved.