473,796 Members | 2,586 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 4808
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
6702
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
5400
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
14134
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
6727
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
3235
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
2584
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
3010
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
2439
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
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9535
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10465
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...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7558
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
5453
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2931
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.