Introduction
In this article, we demonstrate how to report progress information and intermediate results from
an asynchronous method. This article builds on the previous article,
Asynchronous method using C#: Part I.
Using the code
In this article, we do the following changes to our previous example:
Modify the Perform
method for reporting progress.
Implement the ProgressChanged
event.
Define the method ReportProgrss
that synchronizes the
Perform
method and
the ProgressChanged
event.
The Perform method
Here is the Perform
method that we define in our previous example.
private void Perform(string[] files)
{
foreach (string file in files)
{
Thread.Sleep(100);
}
}
Now we modify it in such a way that it reports the progress of the task to
the client code and the processed files.
private void Perform(string[] files)
{
int counter = 0;
foreach (string file in files)
{
Thread.Sleep(100);
counter++;
int percentage = (100 * counter) / files.Length;
ReportProgress(percentage, file);
}
}
After processing the file, we compute the percentage in percentage
and pass it as an argument in
the ReportProgress()
method, which is an example of how
to pass intermediate results to the client code.
Implement the ProgressChanged event
This event is raised whenever an asynchronous method wants to report progress to client code.
public event ProgressChangedEventHandler ProgressChanged
{
add
{
this.progressChangedEventHandler += value;
}
remove
{
this.progressChangedEventHandler -= value;
}
}
private ProgressChangedEventHandler progressChangedEventHandler;
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
if (progressChangedEventHandler != null)
progressChangedEventHandler(this, e);
}
Handling the ProcessChanged event in client code
Register and implement a handler of the ProgressChanged
event.
t.ProgressChanged += new ProgressChangedEventHandler(task_ProgressChange);
static void task_ProgressChange(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("[Task] Progress: {0} %, Current File: {1}",
e.ProgressPercentage, e.UserState);
}
The ReportProgress method
This method calls the ProgressChanged
event through an AsyncOperation
object.
void ReportProgress(int percentProgress, object userState)
{
if (!IsBusy)
return;
async.Post(delegate(object o)
{
ProgressChangedEventArgs e = o as ProgressChangedEventArgs;
OnProgressChanged(e);
},
new ProgressChangedEventArgs(percentProgress, userState));
}
In this series:
Asynchronous method using C#: Part I.
Asynchronous method using C#: Part II.