"ProgressEventArgs - An EventArgs class that can be used whenever you need to raise an event that contains progress information."
The ProgressEventArgs class is the object that is raised by an event and received by any delegate that is subscribed as an event handler. Once created, you can raise this event from any other class that needs to keep the user informed of the progress of an operation.
The ProgressEventArgs class only requires 3 properties:
- The Minimum value
- The Maximum value
- The Current value
public class ProgressEventArgs : System.EventArgs
{
private int minValue;
private int maxValue;
private int currentValue;
public ProgressEventArgs(int minValue, int maxValue, int currentValue)
{
this.minValue = minValue;
this.maxValue = maxValue;
this.currentValue = currentValue;
}
public int MinValue
{
get { return this.minValue; }
}
public int MaxValue
{
get { return this.maxValue; }
}
public int CurrentValue
{
get { return this.currentValue; }
}
}
The next step is to create an event of type EventHandler<ProgressEventArgs> in a class that raises an event containing progress information.
Consider the following class which has a method that simply counts to 100.
In order for this class to raise ProgressEventArgs, the class needs to have an event of type EventHandler<ProgressEventArgs>. In this class it's called CounterIncreased.
public class Foo
{
public event EventHandler<ProgressEventArgs> CounterIncreased;
public void CountTo100()
{
for (int i = 1; i = 100; i++)
{
OnCounterIncreased(new ProgressEventArgs(0, 100, i);
}
}
protected void OnCounterIncreased(ProgressEventArgs e)
{
if (CounterIncreased != null)
CounterIncreased(this, e);
}
}
In our application, we simply need to subscribe to this event and create an event handler for it. In this case, we are incrementing a progress bar.
private void Form1_Load(object sender, EventArgs e)
{
Foo foo = new Foo();
foo.CounterIncreased += new EventHandler<ProgressEventArgs>(Foo_CounterIncreased);
foo.CountTo100();
}
void Foo_CounterIncreased(object sender, ProgressEventArgs e)
{
progressBar1.Minimum = e.MinValue;
progressBar1.Maximum = e.MaxValue;
progressBar1.Value = e.CurrentValue;
}
The beauty of this approach is that we are not passing UI elements into business classes, and also it takes minimal effort to implement. The other useful thing is that the object calling your class does not have to subscribe to the event. In the example above, foo.CountTo100() will work exactly the same regardless of whether the caller has subscribed to the CounterIncreased event.
This article was published on the 24th December 2007