+ Reply to Thread
Results 1 to 2 of 2

Thread: BackgroundWorker tutorial

  1. #1

    BackgroundWorker tutorial

    I need a short tutorial about BackgroundWorker object , i can use threads but i heard that BGW is much better and faster.

    Thanks.
    Last edited by csharpmaster; 11-11-2012 at 09:43 AM.

  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    28
    What would you need ?
    - WindowsApp form
    - Label

    BackgroundWorker Events :
    - DoWork
    - ProgressChanged
    - RunWorkerCompleted
    - RunWorkerAsync [this will start the dowork process]

    Code Snippet :

    Code:
            private BackgroundWorker bgw = new BackgroundWorker();
    
            public Form1()
            {
                InitializeComponent();
    
                bgw.WorkerReportsProgress = true;
                bgw.WorkerSupportsCancellation = true;
                bgw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bgw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            }
    
            
    
            private void Form1_Load(object sender, EventArgs e)
            {
                if (bgw.IsBusy != true)
                {
                    bgw.RunWorkerAsync();
                }
            }
    
            private void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
    
                for (int i = 1; (i <= 10); i++)
                {
                    if ((worker.CancellationPending == true))
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(500);
                        worker.ReportProgress((i * 10));
                    }
                }
            }
            private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                this.label1.Text = (e.ProgressPercentage.ToString() + "%");
            }
            private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if ((e.Cancelled == true))
                {
                    this.label1.Text = "Canceled!";
                }
    
                else if (!(e.Error == null))
                {
                    this.label1.Text = ("Error: " + e.Error.Message);
                }
    
                else
                {
                    this.label1.Text = "Done!";
                }
            }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts