Horje
Reporting Progress from Async Tasks c# Code Example
Reporting Progress from Async Tasks c#
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ProgressBarDemo
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
 
        public void DoSomething(IProgress<int> progress)
        {
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                if (progress != null)
                    progress.Report(i);
            }
        }
 
        private async void btnStart_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            var progress = new Progress<int>(percent =>
            {
                progressBar1.Value = percent;
 
            });
            await Task.Run(() => DoSomething(progress));
        }
    }
}
Source: foxlearn.com
Reporting Progress from Async Tasks c#
public async void StartProcessingButton_Click(object sender, EventArgs e)
{
  // The Progress<T> constructor captures our UI context,
  //  so the lambda will be run on the UI thread.
  var progress = new Progress<int>(percent =>
  {
    textBox1.Text = percent + "%";
  });

  // DoProcessing is run on the thread pool.
  await Task.Run(() => DoProcessing(progress));
  textBox1.Text = "Done!";
}

public void DoProcessing(IProgress<int> progress)
{
  for (int i = 0; i != 100; ++i)
  {
    Thread.Sleep(100); // CPU-bound work
    if (progress != null)
      progress.Report(i);
  }
}
Reporting Progress from Async Tasks c#
public async Task DownloadFileAsync(string fileName, IProgress<int> progress)
{
  using (var fileStream = ...) // Open local file for writing
  using (var ftpStream = ...) // Open FTP stream
  {
    while (true)
    {
      var bytesRead = await ftpStream.ReadAsync(...);
      if (bytesRead == 0)
        return;
      await fileStream.WriteAsync(...);
      if (progress != null)
        progress.Report(bytesRead);
    }
  }
}




Csharp

Related
unity camera movement script Code Example unity camera movement script Code Example
bubble sort recursive c# Code Example bubble sort recursive c# Code Example
how to full screen login form using C# MVC Code Example how to full screen login form using C# MVC Code Example
Go Statement in CSharp Code Example Go Statement in CSharp Code Example
c# yield return ienumerable Code Example c# yield return ienumerable Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10