BackgroundWorker example in C# Windows Application

C# Component BackgroundWorker is used to accomplish time consuming task like mailing, taking Database Backup in a separate thread. First of all, you have to create an instance of BackgroundWorker to use it. Simply, drag and drop BackgroundWorker from ToolBox on your Form to have an instance or you may have your instance programmatically in the following way.


BackgroundWorker backgroundWorkerBackup = new BackgroundWorker();

Now, this is how you can initiate BackgroundWorker using RunWorkerAsync method.


backgroundWorkerBackup.RunWorkerAsync();

Where should you write BackgroundWorker’s jobs? Create a Code Snippet for DoWork Event.


private void backgroundWorkerBackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     // code here
}

If it requires, “Task Completed” Message or Activity can be written at completion of the BackgroundWorker’s task using RunWorkerCompleted Event.


private void backgroundWorkerBackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // code here
}

Moreover, you can check out BackgroundWorker Status.


if (backgroundWorkerBackup.IsBusy)
{
   //Message
}

These are very few basics of BackgroundWorker to start with. Download source code here. In this example, I have written a SQL Server Database Backup Utility using BackgroundWorker. It takes Backup in a remove able device; please do make necessary Connection String correction in App.config File before trying it.

Thanks
A Rahim Khan

Advertisements
    • Prem Kumar
    • September 20th, 2010

    Hi,
    Iam using the threading concept . I have a MainForm which contains a dockpanel. In that main form am creating a child form instance and adding to the mainform dockpanel.

    When am creating the chilform instance it takes long time and freezes my UI.

    But i have background worker for creating Instance. Still am unable to achieve that. Its give a error like control created on different process cannot be created on the parented control of different instance

    • jayden bell
    • May 10th, 2013

    Hi!

    This is very nice article. Thank you for sharing your knowledge. I have find out few other links which described in good way about “DataGrid using BackgroundWorker – C#”. I hope this is very helpful for developers.

    http://www.c-sharpcorner.com/Forums/Thread/54993/

    http://www.mindstick.com/Articles/7f2eeb0d-de48-4496-91c1-4b68a466f4c4/?DataGrid%20using%20BackgroundWorker%20-%20C#

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: