Wednesday, 6 April 2016

How to run a long running Task in Windows Forms with out Freeze the UI

In this post we are going to see how to run a long running task in windows forms with out freezing a UI, Generally if we do any long running operation in a Button click results in Freeze of UI, this is because of UI thread is running with some long running task so busy, now how we can make the Winforms to run a long running task with out Freeze UI..

To do this we have a create a separate thread which is running background from the Main UI thread, we can easily did that by BackgroundWorker class, and also can report the status to the UI.

Let we drag and drop two text box and two labels,  1 progress bar , 1 backgroundworker




Code
**************

    public partial class Calculation : Form
    {
        public Calculation()
        {
            InitializeComponent();
            calcWorker.WorkerReportsProgress = true;
            calcWorker.ProgressChanged += CalcWorker_ProgressChanged;
            calcWorker.DoWork += CalcWorker_DoWork;
            calcWorker.RunWorkerCompleted += CalcWorker_RunWorkerCompleted;
        }

        private void CalcWorker_RunWorkerCompleted(object sender, 
                RunWorkerCompletedEventArgs e)
        {
            button1.Enabled = true;
        }

        private void CalcWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            CalcParams param = e.Argument as CalcParams;

            for (int i = 0; i < 5; i++)
            {
                System.Threading.Thread.Sleep(2000);
                calcWorker.ReportProgress(20 * i);
            }

            int result = param.Num1 + param.Num2;
            calcWorker.ReportProgress(100, result);
        }

        private void CalcWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;

            if(e.ProgressPercentage == 100)
            {
                MessageBox.Show(e.UserState.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
             CalcParams param = new CalcParams() { 
                         Num1 =Convert.ToInt32( textBox1.Text), 
                         Num2 = Convert.ToInt32( textBox2.Text)
              };

            calcWorker.RunWorkerAsync(param);
            button1.Enabled = false;

        }
    }


    public class CalcParams
    {
        public int Num1 { setget; }

        public int Num2 { setget; }
    }


output:
***************






From this post you can see how to do a long running task in windows forms with out freezing UI.

No comments:

Post a Comment