Use IProgress to implement asynchronous programming process notifications, and iprogress Asynchronously
In asynchronous programming, you can use IProgress <in T> to display the progress.
IProgress <in T> only provides the void Report (T value) method. The Report method reports a value of the T type to IProgress, then, the constructor of the IProgress <in T> Implementation class Progress <in T> receives the form parameters of the Action <T> type, and displays the Progress in the UI through this delegate.
First, write a method to Report the progress using the Report method.
public void DoProcessing(IProgress<int> progress)
{
for (int i = 0; i != 100; ++i)
{
Thread.Sleep(100);
if (progress != null)
{
progress.Report(i);
}
}
}
How can I display the progress in the UI?
Implements the IProgress <in T> interface Progress <int T> class, receives an Action <T>, and displays the Progress to the UI through this delegate.
private async void button1_Click(object sender, EventArgs e)
{
// Current thread
var progress = new Progress<int>(percent => { label1.Text = percent + "%"; });
// Thread pool thread
await Task.Run(() => DoProcessing(progress));
Label1.Text = "end ";
}
For example, You Need To asynchronously read a remote file.
public async Task DownloadFileAsync(string fileName, IProgress<int> progress)
{
using(var fileStream...)
{
using(var ftpStream = ...)
{
while(true)
{
// Asynchronously reads data
var bytesRead = await ftpStream.ReadAsync(...);
if(bytesRead == 0)
{
return;
}
// Write data Asynchronously
await fileStream.WriteAsync(...);
if(progress != null)
{
progress.Report(bytesRead);
}
}
}
}
}