Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using Background Worker in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 794
    Comment on it

    To use a background worker class in C#

    1- Create an Instance of Background Class

     BackgroundWorker bgw=new BackgroundWorker();

    2- Create an event handler for the background worker's DoWork event

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
              for (int i = 0; i < dtCustomer.Rows.Count; i++)
           {
    customerName1 = Convert.ToString(dtCustomer.Rows[i][CName]); CFatherName1 =Convert.ToString(dtCustomer.Rows[i][CFatherName]); InsertItems(customerName1, CFatherName1); sucesscustomeritem += 1; }
    }

    3- Create an event handler for the background worker's ProgressChanged event

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    txtItemsAdded.Text = txtItemsAdded.Text + "\n" + Convert.ToString(sucesscustomeritem) + " records      inserted into the database...";
    }

    4- Create an event handler for the RunWorkerCompleted event.

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
     txtItemsAdded.Text = txtItemsAdded.Text + "\n" + Convert.ToString(sucesscustomeritem) + " records  inserted into the database...";
    dispatcherTimer.Stop();
    MessageBox.Show("Records Inserted Succeessfully");
    }

    5- Add the event handlers to the BackgroundWorker instance's events.

    bgw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerDoWork);
    bgw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerProgressChanged);
    bgw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);

    6- Start running the background operation by calling the RunWorkerAsync method.

    private void btnMap_Click(object sender, RoutedEventArgs e)
    { bgw.RunWorkerAsync(); }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: