473,383 Members | 1,792 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

BackgroundWorker class

Hi there,

Can anyone comment on two apparent problems I've noticed with the
"BackgroundWorker" class (e.g., the design pattern itself). The canonical
examples always show a demonstration of a "Cancel" button handler invoking
"BackgroundWorker.CancelAsync()" but two possible problems then arise:

1) What happens if the "Cancel" button handler is running around the same
time that the worker thread is exiting. In this case, the worker thread may
exit in which case the "RunWorkerCompleted()" handler will be invoked as
soon as the "Cancel" handler returns. The "RunWorkerCompletedEventArgs"
argument passed to "RunWorkerCompleted()" will then indicate that the thread
exited either normally or via an exception but not by cancellation even
though the "Cancel" handler just ran!

2) If any dialogs are displayed on the main UI thread while the background
thread is running (say, merely by asking the user to confirm cancellation
when they click the "Cancel" button), then because a dialog pumps messages,
if the background thread ends while a dialog is still on screen then
"RunWorkerCompleted()" will get called prematurely. IOW, using the example
just cited, the confirm "Cancel" dialog may still be on screen at this point
but "RunWorkerCompleted" is now called indicating the thread ended normally
or via an exception which won't be true if the user then confirms
cancellation (moreover, after confirming cancellation, the "Cancel" handler
will then try to cancel the background thread which has already finished and
"RunWorkerCompleted()" won't be called again).

Can anyone comment on these issues. Thanks.
Sep 9 '06 #1
2 5260
What would you have it do? as in, how would you make it better?

Ciaran O'Donnell

"Bob Chambers" wrote:
Hi there,

Can anyone comment on two apparent problems I've noticed with the
"BackgroundWorker" class (e.g., the design pattern itself). The canonical
examples always show a demonstration of a "Cancel" button handler invoking
"BackgroundWorker.CancelAsync()" but two possible problems then arise:

1) What happens if the "Cancel" button handler is running around the same
time that the worker thread is exiting. In this case, the worker thread may
exit in which case the "RunWorkerCompleted()" handler will be invoked as
soon as the "Cancel" handler returns. The "RunWorkerCompletedEventArgs"
argument passed to "RunWorkerCompleted()" will then indicate that the thread
exited either normally or via an exception but not by cancellation even
though the "Cancel" handler just ran!

2) If any dialogs are displayed on the main UI thread while the background
thread is running (say, merely by asking the user to confirm cancellation
when they click the "Cancel" button), then because a dialog pumps messages,
if the background thread ends while a dialog is still on screen then
"RunWorkerCompleted()" will get called prematurely. IOW, using the example
just cited, the confirm "Cancel" dialog may still be on screen at this point
but "RunWorkerCompleted" is now called indicating the thread ended normally
or via an exception which won't be true if the user then confirms
cancellation (moreover, after confirming cancellation, the "Cancel" handler
will then try to cancel the background thread which has already finished and
"RunWorkerCompleted()" won't be called again).

Can anyone comment on these issues. Thanks.
Sep 9 '06 #2
What would you have it do? as in, how would you make it better?

Well, there may not be a "one solution fits all" approach but at the very
least I wouldn't post broken examples. For instance, all
"RunWorkerCompleted()" examples I've seen so far basically look like this:

private void RunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// User cancelled and thread responded
}
else if (e.Error != null)
{
// Thread ended via an exceptin
}
else
{
// Thread ended normally
}
}

The test for "e.Cancelled" is ok but the other two (error or normal exit)
fail to consider that the
"System.Component.BackgroundWorker.CancellationPen ding" flag may still be
"true" indicating the the user cancelled out but it was too late for the
thread to respond. At first glance, the function appears as if it should be
changed to this instead (or something similar):

private void RunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// User cancelled and thread responded
}
else if (!m_BackgroundWorker.CancellationPending)
{
if (e.Error != null)
{
// Thread ended via an exception
}
else
{
// Thread ended normally
}
}
else
{
// User cancelled but it was too late for the thread to respond
}
}

The final "else" clause above will be problematic anyway if the programmer
is now forced to roll back any changes that the worker thread has
effictively completed. My first reaction to all this anyway is that the
entire model should be enhanced so that the worker thread simply needs to
(optionally) inform the main GUI thread that it's reached a point where
cancellation will no longer be an option (normally at or near the end of its
work). The worker thread will then pause while the main GUI thread will
typically respond by disabling its "Cancel" button. The worker thread then
receives notification (via return code) that the "Cancel" button was either
disabled as requested (the worker thread can then wrap up what it's doing),
or notification that the user already pressed the "Cancel" button during
this brief turn-around time. In this case the worker thread will cancel as
usual. The first "RunWorkerCompleted()" function above will then work as
expected. In any case, while I haven't considered all the details yet, more
coordination between the main GUI thread and the worker thread is required
to handle this situation in general. And this doesn't not even consider the
second issue I reaised in my first post which complicates matters further.
Sep 10 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Sebastian Crewe | last post by:
Greetings, I was much encouraged to see the new BackgroundWorker class in .NET v2. On the face of it, much easier to use than the various delegates and events of yore, though I imagine the same...
5
by: Rob R. Ainscough | last post by:
I'm using a BackgroundWorker to perform a file download from an ftp site. Per good code design practices where I separate my UI code from my core logic code (in this case my Download file method in...
3
by: Hardy Wang | last post by:
Hi all, I am migrating a Windows Form application from .Net 1.1 to 2.0. I try to use BackgroundWorker object to handle a very lengthy process. I have a separated class to handle some very complex...
1
by: Bob | last post by:
Hi, I am having trouble seeing how this bolts together. The UI starts a process which involves a long running database update. All Database activity is handled by a class called DT. DT has a...
3
by: ray.ackley | last post by:
Hello all, I have an app that uses a BackgroundWorker() object to read USB data that is being fed in serially (FT245R chip, www.ftdichip.com). It looks just like a serial data stream. Anyhow,...
14
by: =?Utf-8?B?SXNobWFlbA==?= | last post by:
Hi, I have a form with a progress bar on it and wanted to use the BackgroundWorker to be able to update the progress. I looked at examples, run some of them, but in debug, when the code gets to...
2
by: Chris | last post by:
When I try to access the backgroundWorker.CancellationPending property I get the following exception: An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in...
9
by: RvGrah | last post by:
I'm completely new to using background threading, though I have downloaded and run through several samples and understood how they worked. My question is: I have an app whose primary form...
5
by: =?Utf-8?B?RWl0YW4=?= | last post by:
Hello, I need to create a background thread and two (or more) options are available to me: 1. BackgroundWorker 2. Asynch delegate method and BeginInvoke What are the differences between...
0
by: PeterSchwennesen | last post by:
Problems starting a Timer Programmatically within a BackgroundWorker. I am trying to start a Timer inside a Backgroundworker. I want to start the BackGroundWorker and then have a timer tick a...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.