📜  从异步任务报告进度 c# 代码示例

📅  最后修改于: 2022-03-11 14:49:04.446000             🧑  作者: Mango

代码示例3
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 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(percent =>
            {
                progressBar1.Value = percent;
 
            });
            await Task.Run(() => DoSomething(progress));
        }
    }
}