Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of backgroundWorker ? (can i get some sample code to understand ?)

Tags:

c#

what is the purpose of backgroundWorker ? (can i get some sample code to understand ?)

thank's in advance

like image 756
Gold Avatar asked Aug 17 '09 20:08

Gold


People also ask

What is a BackgroundWorker?

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.

What is use of BackgroundWorker in C#?

BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.

What is the use of BackgroundWorker in VB net?

BackgroundWorker enables a simple multithreaded architecture for VB.NET programs. This is more reliable, and easier, than trying to handle threads directly. In the Toolbox pane, please double-click on the BackgroundWorker icon. This will add a BackgroundWorker1 instance to the tray at the bottom of the screen.

What is the difference between BackgroundWorker and thread?

BackgroundWorker has already implemented functionality of reporting progress, completion and cancellation - so you don't need to implement it by yourself. Usage of Thread gives you more control over the async process execution (e.g. thread priority or choosing beetween foreground/background thread type).


3 Answers

The background worker thread is there to help to offload long running function calls to the background so that the interface will not freeze.

Suppose you have something that takes 5 sec to compute when you click a button. During that time, the interface will appear 'frozen': you won't be able to interact with it.

If you used the background worker thread instead, the button event would setup the worker thread and return immediatly. That will allow the interface to keep accepting new events like other button clicks.

As far as code here are 2 examples:

Here the interface will freeze

protected void OnClick( object sender, EventArgs e )
{
    CallLongRunningFunction(); // will take 5 seconds 
}

Here, it won't as the OnClick will return immediately and the long running function will be executed in another thread.

protected void OnClick( object sender, EventArgs e )
{
     BackgroundWorker bg = new BackgroundWorker();
     bg.DoWork += new DoWorkEventHandler(bg_DoWork);
     bg.RunWorkerAsync();
}

void bg_DoWork(object sender, DoWorkEventArgs e)
{
     BackgroundWorker worker = sender as BackgroundWorker;
     CallLongRunningFunction(); // will take 5 secs
}

The difference in behavior is because the call to the background worker thread will not execute in the same thread as the interface, freeing it to continue its normal work.

like image 98
ADB Avatar answered Nov 25 '22 19:11

ADB


The BackgroundWorker is designed to let you run heavy or long operations on a seperate thread to that of the UI. If you were to run a lengthy process on the UI thread, your UI will most likely freeze until the process completes.

However the BackgroundWorker goes a step further by simplifying the threading process for you. If you were to create your own thread to run the heavy or lengthy process you would need to use delegates to access the UI thread to update a progress bar for example. With the BackgroundWorker you don't need any delegates because the BackgroundWorker's ProgressChanged event already runs on the UI thread and you can add your UI updating code there.

To start the BackgroundWorker you need to call RunWorkerAsync():

this.backgroundWorker.RunWorkerAsync();

To manually stop it call CancelAsync()...

this.backgroundWorker.CancelAsync();

And then check the CancellationPending property from within the DoWork event as shown in the below example:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Example heavy operation
    for (int i = 0; i <= 999999; i++)
    {
        // Sleep for 10ms to simulate work
        System.Threading.Thread.Sleep(10);

        // Report the progress now
        this.backgroundWorker.ReportProgress(i);

        // Cancel process if it was flagged to be stopped.
        if (this.backgroundWorker.CancellationPending)
        {
            e.Cancel = true;
            return;
        }
    }
}

I wrote an article about how to use the BackgroundWorker on my blog. You can check it out here: Using the BackgroundWorker Component in C#

like image 21
David Azzopardi Avatar answered Nov 25 '22 19:11

David Azzopardi


It does work in the background by using threads.

like image 20
mcandre Avatar answered Nov 25 '22 19:11

mcandre