Tuesday, 5 November 2013

Background Worker Example in C#

Leave a Comment


How to avoid application "not responding" ..? if you developed one application  for example require to read some big data in database, read big file, or do some complicated task, you need to execute that task in a background worker.

Background worker allow program do the task in a background process like picture above and wont let your application Not responding but actually the program is still work.

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
Read more about BackgroundWorker here

Here the example :

The Code Behind


 private void button1_Click(object sender, EventArgs e)
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);

            bgw.RunWorkerAsync();
            
        }

        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Do process after process complete
            //Example : you can do like close progress bar here
            toolStripStatusLabel1.Text = "Background Worker Complete the task";
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            //Do work process here.        
            toolStripStatusLabel1.Text = "Background Worker do their work now";
            Thread.Sleep(5000);//sleep 10 seconds
        }



The Output






By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.