Harold Finch
Harold Finch

Reputation: 586

BackgroundWorker not working properly

I'm using a background worker because some method in my program need time for download the data from internet. This method "block" for 5-6 second the software, so I want use the background worker to execute the method like a thread. In my class I've create this:

 private BackgroundWorker worker = new BackgroundWorker();

after, in ComboBox selection changed, I call the BackgroundWorker in this way:

worker.DoWork += new DoWorkEventHandler(doWork);

the doWork method contains:

public void doWork(object sender, DoWorkEventArgs e)
{
        classifica.getClassifica(); //call the method from another class
}

now my problem is that the method doWork isn't called by the BackgroundWorker. What I doing wrong?

Upvotes: 0

Views: 6041

Answers (4)

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6039

You have to call worker.RunWorkerAsync(); to start the worker. There is also an overload to allow you to pass an object parameter to your DoWork function:

void RunWorkerAsync(object argument)

You can also add a handler so you will know when the worker is done: worker.RunWorkerCompleted. In this handler you can access the DataGrid because it will be in the UI thread (assuming you created the worker in the UI thread)

Upvotes: 0

Equalsk
Equalsk

Reputation: 8194

I think you're looking for this:

if (worker.IsBusy != true)
{
    worker.RunWorkerAsync();
}

Although unless you're set on a BackGroundWorker or can't target .NET 4.5 then I highly recommend WebClient.DownloadDataAsync.

Use it like this:

static void DownloadData()
{
    string url = "http://google.com";
    WebClient client = new WebClient();
    client.DownloadDataCompleted += DownloadDataCompleted;
    client.DownloadDataAsync(new Uri(url));
}

static void DownloadDataCompleted(object sender,
DownloadDataCompletedEventArgs e)
{
    // Handle returned data here
}

Does all this for you without using anything else. Simple!

Upvotes: 0

Nicolas C
Nicolas C

Reputation: 754

You need to start the background worker this way

if (bw.IsBusy != true)
{
    bw.RunWorkerAsync();
}

Follow this for more details https://msdn.microsoft.com/fr-fr/library/cc221403(v=vs.95).aspx

Upvotes: 0

Panh
Panh

Reputation: 225

You have to start the worker.

 worker.RunWorkerAsync();

Upvotes: 2

Related Questions