Friday 15 September 2017

Progress Bar using Task in C#

Task ProgressBar Project
https://drive.google.com/open?id=0B6jghOdcFjiqZk9MQ2Z4bS1JN28

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestTask
{
   public class ProgressReport
    {
        public int percenteComplete { get; set; }
    }
}



--------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace TestTask
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Task ProcessData(List<string> lst, IProgress<ProgressReport> progress)
        {
            int index = 1;
            int totalProcess=lst.Count;
            var progressReport = new ProgressReport();
            return Task.Run(() =>
            {
                for (int i=0; i < totalProcess; i++)
                {
                    progressReport.percenteComplete = (index++ * 100) / totalProcess;
                    progress.Report(progressReport);
                    Thread.Sleep(10);
                }
            });
        
        }


         

        private async void btnStart_Click(object sender, EventArgs e)
        {
            List<string> lst = new List<string>();
            for (int i=0; i < 1000; i++)
            {
                lst.Add(i.ToString());
            }
            lblStatus.Text = "working...";

            var progress = new Progress<ProgressReport>();
            progress.ProgressChanged+=(o,report)=>{
                lblStatus.Text = string.Format("Progressing....{0}%", report.percenteComplete);
                progressBar.Value = report.percenteComplete;
                progressBar.Update();
            };

            await ProcessData(lst, progress);
            lblStatus.Text = "done";
        }
    }
}

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0