473,805 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cancel BackgroundWorke r

How do you cancel a BackgroundWorke r?

For this BackgroundWorke r:

bgWorker.Worker ReportsProgress = true;
bgWorker.Worker SupportsCancell ation = true;

I have tried this, but it never exits the do...while loop:

if (bgWorker.IsBus y == true) {
bgWorker.Cancel Async();
}
do {
Thread.Sleep(0) ;
} while (bgWorker.IsBus y == true);

I tried removing the do...while loop, but then I get errors because the
thread is still being used!
Sep 11 '08 #1
7 4809
On Thu, 11 Sep 2008 11:24:00 -0700, jp2msft
<jp*****@discus sions.microsoft .comwrote:
How do you cancel a BackgroundWorke r?
See the MSDN documentation for the class. It includes an example of a
cancelable BackgroundWorke r.

The short story: your DoWork handler needs to take into account the
possibility of cancellation, checking for that condition at opportune
moments during processing and terminating early when canceled.

From the docs for BackgroundWorke r.CancelAsync() :

The worker code should periodically check the
CancellationPen ding property to see if it has
been set to true.

Pete
Sep 11 '08 #2
I copied their example, and I even have my thread checking to see if it has
been cancelled within its loops:

if (worker.Cancell ationPending == true) {
e.Cancel = true;
return;
}

This part of the code is triggered, but when this happens, the code does not
enter the bgWorker_Progre ssChanged or bgWorker_RunWor kerCompleted event
handlers.

Because of this, my do...while loop never exits.

How is this fixed?

BTW: Thanks for your help, too!

"Peter Duniho" wrote:
See the MSDN documentation for the class. It includes an example of a
cancelable BackgroundWorke r.

The short story: your DoWork handler needs to take into account the
possibility of cancellation, checking for that condition at opportune
moments during processing and terminating early when canceled.

From the docs for BackgroundWorke r.CancelAsync() :

The worker code should periodically check the
CancellationPen ding property to see if it has
been set to true.

Pete
Sep 11 '08 #3
On Thu, 11 Sep 2008 13:17:01 -0700, jp2msft
<jp*****@discus sions.microsoft .comwrote:
I copied their example, and I even have my thread checking to see if it
has
been cancelled within its loops:

if (worker.Cancell ationPending == true) {
e.Cancel = true;
return;
}

This part of the code is triggered, but when this happens, the code does
not
enter the bgWorker_Progre ssChanged or bgWorker_RunWor kerCompleted event
handlers.

Because of this, my do...while loop never exits. [...]
Unless you post a concise-but-complete code sample that demonsrates
exactly what you're doing, it's not possible to say what you're doing
wrong. The RunWorkerComple ted event definitely should be raised, but
there's nothing in the code you post that proves that you're handling it,
never mind that it would affect the loop you posted.

The most likely explanation is that the loop you posted is executing on
the main GUI thread, and of course doing so would cause all sorts of
issues, including this one. But without all the code, it's impossible to
say for sure what's going on.

That said, I'll point out that just from the little code you've posted,
it's clear that your basic strategy is simply wrong. There is no sense in
handing off work to a different thread only to have the current thread sit
and wait for it to be done. There also is _especially_ no sense in
writing a "busy wait" as you've done here, where the only thing the loop
does is repeatedly check for a specific condition. Even in situations
where it makes sense for a thread to wait for something to happen (and
this doesn't appear to be such a situation), there are correct ways to
wait, such as using a WaitHandle sub-class, that don't consume CPU
resources uselessly as your code does.

If you can provide a concise-but-complete code sample, I'm sure I or
someone else can provide more useful advice. Until then, I remain
unoptimistic. :)

Pete
Sep 11 '08 #4
I wished I could provide an attachment, but I can't.

I added one ugly Application.DoE vents() to the wait loop, and my thread went
into the RunWorkerComple ted section.

I could email you the file, if you are interested. You can send your email
address to me at jpool at aaon dot com.
Sep 11 '08 #5
On Thu, 11 Sep 2008 14:17:03 -0700, jp2msft
<jp*****@discus sions.microsoft .comwrote:
I wished I could provide an attachment, but I can't.
Sure you can. If you want the best answer, you must.

It doesn't have to be the full code you're working with. In fact, it
typically shouldn't be. But it does have to be complete, and it does have
to reproduce the problem.

Every question ever posted to this newsgroup has such as
"concise-but-complete" code sample that goes along with the question.
Often the person posting the question fails to include the sample, but one
always exists.
I added one ugly Application.DoE vents() to the wait loop, and my thread
went
into the RunWorkerComple ted section.
Don't do that. Calling DoEvents() is simply bad generally (the biggest
issue is that it introduces re-entrancy to code that has almost certainly
not been designed with re-entrancy in mind), and in this case it only
emphasizes how defective your current design is (you should never be
blocking the GUI thread, and I'll reiterate that having one thread just
sit and wait for another thread is always the wrong thing to do).
I could email you the file, if you are interested. You can send your
email
address to me at jpool at aaon dot com.
Any code sample I'd be willing to read through would be appropriate to be
posted here.

That said, based on your reply, it sounds like you've confirmed my guess
as to what's wrong. The correct resolution is to fix your design so that
the main GUI thread isn't waiting on the worker thread at all. Put all of
the logic that occurs after the wait into a method that can be called by
the RunWorkerComple ted event handler, or into that handler's method
itself. The main GUI thread should simply start the worker and then
return.

Pete
Sep 11 '08 #6
Ok, here is a small test section that I have put together to illustrate my
problem:

We have an SQL query that takes 60-120 seconds to run for each employee (the
SqlCommand's CommandTimeout is set to 120 seconds and this seems to give the
queries enough time).

public static string m_fmtSql = "SELECT LOTS OF STUFF WHERE EMPLOYEE='{0}'" ;
public static SqlConnection m_conn; // set elsewhere

void worker_DoWork(o bject sender, DoWorkEventArgs e) {
List<stringEmpl oyees = (List<string>)e .Argument;
List<stringErro rs = new List<string>();
List<stringResu lts = new List<string>();
BackgroundWorke r worker = sender as BackgroundWorke r;
int Count = 0;
foreach (string person in Employees) {
if (worker.Cancell ationPending == true) {
e.Cancel = true;
return;
}
Count++;
worker.ReportPr ogress(100 * Count / Employees.Count );
DataTable dt = new DataTable();
string sql = string.Format(m _fmtSql, person);
using (SqlDataAdapter da = new SqlDataAdapter( sql, m_conn)) {
try {
da.Fill(dt); // this step takes 60-120 seconds to run
} catch (SqlException err) {
Errors.Add(err. Message);
}
}
if (0 < dt.Rows.Count) {
string fmt = "{0};{1};{2};{3 };{4};{5};{6}";
string var1, var2, var3, var4, var5;
int var6, var7;
// work with data, manipulate some figures, then add it to the results
string result
= string.Format(f mt, var1, var2, var3, var4, var5, var6, var7);
Results.Add(res ult);
}
}
e.Result = Results;
}

void worker_RunWorke rCompleted(obje ct sender, RunWorkerComple tedEventArgs e) {
if (e.Error != null) {
// display error
} else if (e.Cancelled == true) {
// display that status
} else if (e.Result is List<string>) {
List<stringResu lts = (List<string>)e .Result;
DataGridView1.R ows.Clear();
foreach (string line in Results) {
string[] data = line.Split(new char[] { ';' });
DataGridView1.R ows.Add(data);
}
}
}

void BtnCancel_Click (object sender, EventArgs e) {
if ((WorkerThread. IsBusy == true) &&
(WorkerThread.S upportsCancella tion == true)) {
WorkerThread.Ca ncelAsync();
// Here is the point of concern:
// since the SQL call could take up to 2 full minutes to complete,
// our Users are liable to try running the report again while
// the thread is still active.
// So, the solution is to disable the "Run Report" button until
// this thread has finished:
BtnRunReport.En abled = false;
do {
Thread.Sleep(0) ;
} while (WorkerThread.I sBusy == true);
BtnRunReport.En abled = true;
// The problem is:
// This code is so busy in the loop, that the
// "RunWorkerCompl eted" code does not have a chance to run.
// If I write in the ugly "Application.Do Events();" within the
do...while loop,
// the application will stop itself, but that is a bad fix.
}
}
Sep 12 '08 #7
On Fri, 12 Sep 2008 09:14:07 -0700, jp2msft
<jp*****@discus sions.microsoft .comwrote:
Ok, here is a small test section that I have put together to illustrate
my
problem:
Please see http://www.yoda.arachsys.com/csharp/complete.html

Based on what you've written so far in this thread, I believe my previous
comments should be sufficient in helping you fix your code. But if you
feel there's a need for further elaboration, you need to post a true
concise-but-complete code sample. What you just posted is neither.
Sep 12 '08 #8

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

Similar topics

2
6704
by: Sagaert Johan | last post by:
The backgroundworker contains a blocking call to UDPClient.Receive How do i unlock this thread so the backgroundworker can be cancelled ? Johan
2
5401
by: Steve | last post by:
After running into a design wall with my traditional thread approach, I realized that a BackgroundWorker object would fit my needs pretty good. Never really used them before. In a nutshell, my problem is cancelling the worker. I've read the MSDN docs, checked google and haven't found a solution. The problem is, once I make a call to cancellAsync() (I check for CancellationPending in my DoWork handler) and WorkerComplete fires, the...
5
14135
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 my FileIO class) I've established Public Event in my core logic classes along with RaiseEvents (that will updated a progress bar on the UI side). This all works great when I'm NOT using Threading (BackgroundWorker), however, as soon as I...
1
6728
by: David Veeneman | last post by:
Does anyone knmow why an asynchronous worker method would crash if the e.Cancel method is set to true, but not otherwise? I'm working on a demo app with an asynchronous call, using the .NET 2.0 BackgroundWorker component. The app works fine if I let the worker method proceed to completion. But if I cancel the worker method, it crashes. Specifically, if I set the DoWorkEventArgs.Cancel property to true, the worker thread crashes at the...
1
3236
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 progress event. So I added a bw to the form. The Dowork Calls a method which instantiates a DT and calls its Dataprocessing method.
9
18036
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 will almost always lead to the user opening a certain child window that's fairly resource intensive to load. Is it possible to load this form in a backgroundworker and then use the Show method and hide method as necessary? Anyone know of
4
2585
by: Sin Jeong-hun | last post by:
This is what I've always been wondered. Suppose I've created a class named Agent, and the Agent does some lengthy job. Of course I don't want to block the main window, so the Agent does the job in a separate thread. If the job is progressed it fires an event, and the main window handled the event by changing the value of a progress bar. The problem is that this event is fired in another thread so when the handler in the main window tries...
0
3013
by: Smokey Grindel | last post by:
I have a search function that runs in a background worker which can run long.. I want the user to be able to cancel that then run another search... but sometimes it throws an exception saying System.InvalidOperationException: This BackgroundWorker is currently busy and cannot run multiple tasks concurrently. What I did before the search button was pressed again was check if the worker is busy and if it is cancel the current search then...
16
2441
by: parez | last post by:
I start a BackGroundWorker to populate a grid. It is started off in the ui layer The thread follows( cannot think of a better word) the path UI->Layer1->Layer2->Communication Layer and it blocks (the server is executing somthing where which takes time)
0
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.