Why am I getting an exception "cannot access disposed object" sometimes? - c#

I have this code in my background DoWork event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
{
soundPlay = true;
blinking_label();
NudgeMe();
}
else
{
soundPlay = false;
stop_alarm = true;
}
cpuView();
gpuView();
}
}
}
In the cpuView() method I have this code:
if (InvokeRequired)
{
this.Invoke(new Action(() => data = new List<string>()));
this.Invoke(new Action(() => data.Add("Gpu Temeprature --- " + sensor.Value.ToString())));
this.Invoke(new Action(() => listBox1.DataSource = null));
this.Invoke(new Action(() => listBox1.DataSource = data));
this.Invoke(new Action(() => listBox1.Invalidate()));
}
The exception/error was this time on the line:
this.Invoke(new Action(() => data = new List<string>()));
And this is my Form1 closing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
}
}
}
The error/exception happened once i quit my application clicked on the red x on the top right corner and selected YES to quit.
What should I do ?

So part of the issue here is that you're not leveraging the functionality that a BGW gives you. If you're calling Invoke from inside of DoWork it means you're not really using a BGW to do it's job. In your case, you should just be calling ReportProgress on the BGW, and then have a ProgressChanged event handler that updates the UI based on the progress. You can pass in a parameter that represents the data to update the UI with, so you can construct your list inside of DoWork, pass it via ReportProgress, and then set the DataSource in the ProgressChanged event handler.
Now the BGW is responsible for not reporting progress once the worker has been canceled.

As a Form is closed, its child controls and the form itself are disposed. However, WinForms continues to process pending Invokes on the UI thread. That's why it raises a "cannot access disposed objects".
Application.DoEvents() is often described as the evil, but its job is to process all pending messages on the UI thread.
Having the background threads finished in the Close event is not enough.
That's why I suggest you to add an Application.DoEvents() before any Dispose, so the pending Invokes are being flushed, then the form will Close gracefully.
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
}
Application.DoEvents();
}
In case of the Application.DoEvents() is too hacky for you, you can swallow the ObjectDisposedException by using a extension method that encapsulates the InvokeRequired pattern:
public static void InvokeIfRequired(this Control control, Action action)
{
try
{
if (control.IsDisposed)
return;
if (control.InvokeRequired)
control.Invoke(action);
else
action();
}
catch (ObjectDisposedException)
{
// There is nothing much we can do when an Invoke is pending on a disposed control
// the other exceptions will bubble up normally
}
}

Related

C# Backgroundworker closing form

I am having an issue with a background worker.
When i'm cancelling the backgroundworker, it closes the form too, i don't want it.
I just want to stop the backgroundworker, and keep the form on the screen, and saying a message to the user like "Program stopped by user"
public BackgroundWorker bw = new BackgroundWorker() { WorkerSupportsCancellation = true };
public Form1()
{
bw.WorkerSupportsCancellation = true;
InitializeComponent();
}
private void stopChild_Click(object sender, EventArgs e)
{
if (bw.IsBusy)
{
bw.CancelAsync();
this.Dispose();
}
}
public void startParListe()
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
if (bw.IsBusy != true)
bw.RunWorkerAsync();
}
public void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker ;
for (int i = 0; i < countPlages; i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
#do something else
}
}
So, when the user click on the "stopChild" button, it is supposed to send a CancelSignal to my BWorker.
Everytime my BWorker is working, i'm checking for this CancellationPending Signal before doing anything.
With this code, the form closes when clicking on the "stopChild"
And when i remove the "this.Dispose()", the BWorker doesn't stop. Why ?
You don't properly process the CancellationPending:
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
I am not sure what e.Cancel is supposed to do, but you still continue to do work in your for loop since you don't leave the loop. Change it to:
if (worker.CancellationPending) // btw - avoid unnecessarily verbous code
{
break;
}
The backgroundworker does not close your form, this.Dispose does. You need to omit it. The reason why this.Dispose helped stop the background worker is because it is owned by the form, so closing the form also closees the worker. But once you fix the cancellation as described above, you should not need Dispose any longer
You should break out of the loop when you set e.Cancel to true (also, this.Dispose() is closing your form:
public void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker ;
for (int i = 0; i < countPlages; i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
#do something else
}
}

How to close object of form created by Application.run() method in C#?

I am working on C# win form application.My problem is when i click on menu i created one separate thread which is showing the progress(splash progress form). When i abort thread, progress form still display..! but when i move mouse pointer over the form it disappear
immediately..!
Following is my code
Thread progressThread = new Thread(() => Application.Run(new frmOperationProgress()));
progressThread.IsBackground = true;
progressThread.Start();
//Some work
progressThread.Abort();
How to close this progress form object in c#
The problem is using Abort - it's not generally recommended because there is no guarantee that it's going to do what you expect (in your case hide the form).
Best to add proper cancellation support into your thread and handle hiding the splash screen directly.
Please never ever use Abort(). This kind of work is best done trough BackgroundWorker; if you insist on Thread
Try:
var form = new frmOperationProgress();
Thread progressThread = new Thread(() => Application.Run(form));
progressThread.IsBackground = true;
progressThread.Start();
//Some work
form.ExternalClose();
Where ExternalClose is method of form like this:
public void ExternalClose() {
if (InvokeRequired) {
Invoke(new MethodInvoker(() => { ExternalClose(); }));
} else {
Close();
}
}
Solution using BackgroundWorker:
In backround worker you have to do UI stuff in ProgressChanged event (which is running in UI thread) and do the dirty work in DoWork event (background thread).
FormMain.cs: (Form with single BackgroundWorker control, named "backgroundWorker1", with wired up events backgroundWorker1_DoWork, backgroundWorker1_ProgressChanged and WorkerReportsProgress set to true)
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleApplication1 {
public partial class FormMain : Form {
private FormProgress m_Form;
public FormMain() {
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
backgroundWorker1.ReportProgress(0, "hello");
Thread.Sleep(2000);
backgroundWorker1.ReportProgress(20, "world");
Thread.Sleep(2000);
backgroundWorker1.ReportProgress(40, "this");
Thread.Sleep(2000);
backgroundWorker1.ReportProgress(60, "is");
Thread.Sleep(2000);
backgroundWorker1.ReportProgress(80, "simple");
backgroundWorker1.ReportProgress(100, "end");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
if (e.ProgressPercentage == 0 && m_Form == null) {
m_Form = new FormProgress();
m_Form.Show();
}
if (e.ProgressPercentage == 100 && m_Form != null) {
m_Form.Close();
m_Form = null;
return;
}
var message = (string)e.UserState;
m_Form.UpdateProgress(e.ProgressPercentage, message);
}
}
}
Where FormProgress is simple form with ProgressBar progressBar1 and Label label1 and one extra method:
public void UpdateProgress(int percentage, string message) {
this.progressBar1.Value = percentage;
this.label1.Text = message;
}
You can just close your form and the thread (which is blocked by the message loop of that form) will be ended naturally:
var yourForm = new frmOperationProgress();
//Start it
Thread progressThread = new Thread(() => Application.Run(yourForm));
progressThread.IsBackground = true;
progressThread.Start();
//....
//close it
yourForm.Invoke((Action)(() => yourForm.Close()));

How to stop BackgroundWorker on Form's Closing event to avoid RaceOnRCWCleanup error and to aovid form1 dispose before backgroundworker finish? [duplicate]

This question already has answers here:
How to stop BackgroundWorker on Form's Closing event?
(12 answers)
Closed 9 years ago.
In Form1 top i added this:
bool completed;
AutoResetEvent autoreset;
In the constructor i did:
completed = false;
autoreset = new AutoResetEvent(false);
In the backgroundworker DoWork event i did:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
completed = true;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
{
soundPlay = true;
NudgeMe();
}
else
{
soundPlay = false;
stop_alarm = true;
}
tempCpuValue = Core.cpuView(pauseContinueDoWork,cpu,this,data,tempCpuValue,button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork,data,tempGpuValue,button1);
this.Invoke(new Action(() => data = new List<string>()));
tempCpuValue = Core.cpuView(pauseContinueDoWork, cpu, this, data, tempCpuValue, button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork, data, tempGpuValue, button1);
this.Invoke(new Action(() => listBox1.DataSource = null));
this.Invoke(new Action(() => listBox1.DataSource = data));
//listBox1.DataSource = data;
}
}
autoreset.Set();
}
Then in the Form1 closing event i did:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
if (completed == true)
{
this.backgroundWorker1.CancelAsync();
autoreset.WaitOne();
}
}
}
When it's doing the WaitOne() the form just back show up in the middle and the program is freezing all i can do is in the visual studio Debug>Stop Debugging
I wanted to do it to aovid exceptions im getting sometimes RaceOnRCWCleanup something about multi threadings.
And sometimes when closing the program i got on another class this exception:
System.ObjectDisposedException was unhandled by user code
HResult=-2146232798
Message=Cannot access a disposed object.
Object name: 'Form1'.
Source=System.Windows.Forms
ObjectName=Form1
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at HardwareMonitoring.Core.cpuView(Boolean pause, CpuTemperature cpuTemp, Form1 f1, List`1 myData, Nullable`1 myCpuTemp, Button b1) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Core.cs:line 55
at HardwareMonitoring.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 427
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
Like the form1 disposed before the backgroundworker finished the job and the backgrounddworker dowork event is using this class methods.
Suppose Bgw is you backgroundworker first you will set :
Bgw.WorkerSupportsCancellation = true;
then in you DoWork delegate you will have to check whether Bgw.CancellationPending is true or false.
If it is true that means backgroundworker has been canceled and you will have to abort the function if not continue as it is.
Try this:
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker1.CancellationPending)
{
if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
{
soundPlay = true;
NudgeMe();
}
else
{
soundPlay = false;
stop_alarm = true;
}
tempCpuValue = Core.cpuView(pauseContinueDoWork, cpu, this, data, tempCpuValue, button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork, data, tempGpuValue, button1);
this.BeginInvoke(new Action(() => data = new List<string>()));
tempCpuValue = Core.cpuView(pauseContinueDoWork, cpu, this, data, tempCpuValue, button1);
tempGpuValue = Core.gpuView(pauseContinueDoWork, data, tempGpuValue, button1);
this.BeginInvoke(new Action(() => listBox1.DataSource = null));
this.BeginInvoke(new Action(() => listBox1.DataSource = data));
}
completed = true;
autoreset.Set();
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
if (!completed)
{
this.backgroundWorker1.CancelAsync();
Hide(); // hide the form while waiting for the bw to terminate
autoreset.WaitOne();
}
}
}
I've changed the calls from Invoke to BeginInvoke this should mitigate your problems.

Closing the form when backgroundWorker stops working

I'm working on an application that should read the data from Mifare smart card. I have to create a form will check the Mifare reader periodically and when the card is in range, read its serial number and send it to the parent form. I managed to get the background worker to read the serial number, but I can't close the form from it due to cross thread calling error it would cause. Is there a way to monitor the work that backGroundWorker does, and when it successfully reads the card ID, to stop it and close the child form?
This is the code I'm using in the DoWork method:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (!worker.CancellationPending)
{
MifareReader.CommPort = 4;
MifareReader.PortOpen = true;
MifareReader.mfAutoMode(true);
MifareReader.mfRequest();
if (CardID == "0" || CardID == string.Empty)
{
MifareReader.mfRequest();
CardID = MifareReader.mfAnticollision().ToString();
MifareReader.mfHalt();
}
else if (CardID != "0" && CardID != string.Empty)
{
MessageBox.Show(ObrnutiID);
worker.CancelAsync();
}
MifareCitac.mfHalt();
}
}
This code does it's job, but I have to manually close the form. Is there a way to check if the CardID variable changes it's value in the main thread and if it does, close the form.
I tried to solve this problem by using a timer, but when I do that, the timer blocks the main form thread, and I can't close it manually (which of course I have to be able). Can you please suggest a way to solve this problem?
You can use the BackgroundWorker.RunWorkerCompleted event to monitor when the BackgroundWorker is done.
Occurs when the background operation has completed, has been canceled, or has raised an exception.
From there, you could close the form programmatically.
You can write your BackgroundWorker so that it returns when it has finished its work.
Then in your main form, subscribe to the BackgroundWorker.RunWorkerCompleted and respond appropriately, presumably by just closing the form.
Add RunWorkerCompleted event from your backgroundWorker:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close() // Closes the form.
}
You can avoid cross-thread calling error by checking InvokedRequired and try to BeginInvoke using delegates.
As others mentioned, here is how to implement the BackgroundWorker.RunWorkerCompleted event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bool found = false;
var worker = sender as BackgroundWorker;
while (!worker.CancellationPending && !found)
{
MifareReader.CommPort = 4;
MifareReader.PortOpen = true;
MifareReader.mfAutoMode(true);
MifareReader.mfRequest();
if (CardID == "0" || CardID == string.Empty)
{
MifareReader.mfRequest();
CardID = MifareReader.mfAnticollision().ToString();
MifareReader.mfHalt();
}
else
{
e.Result = ObrnutiID;
found = true;
MifareCitac.mfHalt();
}
}
if (worker.CancellationPending)
{
e.Cancel = true;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
// The operation completed normally.
string msg = String.Format("Result = {0}", e.Result);
MessageBox.Show(msg);
}
this.Close() // Closes the form.
}

How to wait for a BackgroundWorker to cancel?

Consider a hypothetical method of an object that does stuff for you:
public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
}
}
How can one wait for a BackgroundWorker to be done?
In the past people have tried:
while (_worker.IsBusy)
{
Sleep(100);
}
But this deadlocks, because IsBusy is not cleared until after the RunWorkerCompleted event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)
Others have add suggested kludging it into:
while (_worker.IsBusy)
{
Application.DoEvents();
}
The problem with that is that is Application.DoEvents() causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).
I would hope to use some solution involving Event synchronization objects, where the code waits for an event - that the worker's RunWorkerCompleted event handlers sets. Something like:
Event _workerDoneEvent = new WaitHandle();
public void CancelDoingStuff()
{
_worker.CancelAsync();
_workerDoneEvent.WaitOne();
}
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
_workerDoneEvent.SetEvent();
}
But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.
So how can you wait for an BackgroundWorker to finish?
Update
People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyWork;
worker.RunWorkerAsync();
WaitForWorkerToFinish(worker);
That is not it, that is not what I'm doing, and that is not what is being asked here. If that were the case, there would be no point in using a background worker.
If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):
private BackgroundWorker worker = new BackgroundWorker();
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
}
public void Cancel()
{
worker.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(!e.Cancel)
{
// do something
}
_resetEvent.Set(); // signal that worker is done
}
There is a problem with this response. The UI needs to continue to process messages while you are waiting, otherwise it will not repaint, which will be a problem if your background worker takes a long time to respond to the cancel request.
A second flaw is that _resetEvent.Set() will never be called if the worker thread throws an exception - leaving the main thread waiting indefinitely - however this flaw could easily be fixed with a try/finally block.
One way to do this is to display a modal dialog which has a timer that repeatedly checks if the background worker has finished work (or finished cancelling in your case). Once the background worker has finished, the modal dialog returns control to your application. The user can't interact with the UI until this happens.
Another method (assuming you have a maximum of one modeless window open) is to set ActiveForm.Enabled = false, then loop on Application,DoEvents until the background worker has finished cancelling, after which you can set ActiveForm.Enabled = true again.
Almost all of you are confused by the question, and are not understanding how a worker is used.
Consider a RunWorkerComplete event handler:
private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!e.Cancelled)
{
rocketOnPad = false;
label1.Text = "Rocket launch complete.";
}
else
{
rocketOnPad = true;
label1.Text = "Rocket launch aborted.";
}
worker = null;
}
And all is good.
Now comes a situation where the caller needs to abort the countdown because they need to execute an emergency self-destruct of the rocket.
private void BlowUpRocket()
{
if (worker != null)
{
worker.CancelAsync();
WaitForWorkerToFinish(worker);
worker = null;
}
StartClaxon();
SelfDestruct();
}
And there is also a situation where we need to open the access gates to the rocket, but not while doing a countdown:
private void OpenAccessGates()
{
if (worker != null)
{
worker.CancelAsync();
WaitForWorkerToFinish(worker);
worker = null;
}
if (!rocketOnPad)
DisengageAllGateLatches();
}
And finally, we need to de-fuel the rocket, but that's not allowed during a countdown:
private void DrainRocket()
{
if (worker != null)
{
worker.CancelAsync();
WaitForWorkerToFinish(worker);
worker = null;
}
if (rocketOnPad)
OpenFuelValves();
}
Without the ability to wait for a worker to cancel, we must move all three methods to the RunWorkerCompletedEvent:
private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!e.Cancelled)
{
rocketOnPad = false;
label1.Text = "Rocket launch complete.";
}
else
{
rocketOnPad = true;
label1.Text = "Rocket launch aborted.";
}
worker = null;
if (delayedBlowUpRocket)
BlowUpRocket();
else if (delayedOpenAccessGates)
OpenAccessGates();
else if (delayedDrainRocket)
DrainRocket();
}
private void BlowUpRocket()
{
if (worker != null)
{
delayedBlowUpRocket = true;
worker.CancelAsync();
return;
}
StartClaxon();
SelfDestruct();
}
private void OpenAccessGates()
{
if (worker != null)
{
delayedOpenAccessGates = true;
worker.CancelAsync();
return;
}
if (!rocketOnPad)
DisengageAllGateLatches();
}
private void DrainRocket()
{
if (worker != null)
{
delayedDrainRocket = true;
worker.CancelAsync();
return;
}
if (rocketOnPad)
OpenFuelValves();
}
Now I could write my code like that, but I'm just not gonna. I don't care, I'm just not.
You can check into the RunWorkerCompletedEventArgs in the RunWorkerCompletedEventHandler to see what the status was. Success, canceled or an error.
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
Console.WriteLine("The worker was cancelled.");
}
}
Update: To see if your worker has called .CancelAsync() by using this:
if (_worker.CancellationPending)
{
Console.WriteLine("Cancellation is pending, no need to call CancelAsync again");
}
You don't wait for the background worker to complete. That pretty much defeats the purpose of launching a separate thread. Instead, you should let your method finish, and move any code that depends on completion to a different place. You let the worker tell you when it's done and call any remaining code then.
If you want to wait for something to complete use a different threading construct that provides a WaitHandle.
Why can't you just tie into the BackgroundWorker.RunWorkerCompleted Event. It's a callback that will "Occur when the background operation has completed, has been canceled, or has raised an exception."
I don't understand why you'd want to wait for a BackgroundWorker to complete; it really seems like the exact opposite of the motivation for the class.
However, you could start every method with a call to worker.IsBusy and have them exit if it is running.
Hm maybe I am not getting your question right.
The backgroundworker calls the WorkerCompleted event once his 'workermethod' (the method/function/sub that handles the backgroundworker.doWork-event) is finished so there is no need for checking if the BW is still running.
If you want to stop your worker check the cancellation pending property inside your 'worker method'.
The workflow of a BackgroundWorker object basically requires you to handle the RunWorkerCompleted event for both normal execution and user cancellation use cases. This is why the property RunWorkerCompletedEventArgs.Cancelled exists. Basically, doing this properly requires that you consider your Cancel method to be an asynchronous method in itself.
Here's an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace WindowsFormsApplication1
{
public class AsyncForm : Form
{
private Button _startButton;
private Label _statusLabel;
private Button _stopButton;
private MyWorker _worker;
public AsyncForm()
{
var layoutPanel = new TableLayoutPanel();
layoutPanel.Dock = DockStyle.Fill;
layoutPanel.ColumnStyles.Add(new ColumnStyle());
layoutPanel.ColumnStyles.Add(new ColumnStyle());
layoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
_statusLabel = new Label();
_statusLabel.Text = "Idle.";
layoutPanel.Controls.Add(_statusLabel, 0, 0);
_startButton = new Button();
_startButton.Text = "Start";
_startButton.Click += HandleStartButton;
layoutPanel.Controls.Add(_startButton, 0, 1);
_stopButton = new Button();
_stopButton.Enabled = false;
_stopButton.Text = "Stop";
_stopButton.Click += HandleStopButton;
layoutPanel.Controls.Add(_stopButton, 1, 1);
this.Controls.Add(layoutPanel);
}
private void HandleStartButton(object sender, EventArgs e)
{
_stopButton.Enabled = true;
_startButton.Enabled = false;
_worker = new MyWorker() { WorkerSupportsCancellation = true };
_worker.RunWorkerCompleted += HandleWorkerCompleted;
_worker.RunWorkerAsync();
_statusLabel.Text = "Running...";
}
private void HandleStopButton(object sender, EventArgs e)
{
_worker.CancelAsync();
_statusLabel.Text = "Cancelling...";
}
private void HandleWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
_statusLabel.Text = "Cancelled!";
}
else
{
_statusLabel.Text = "Completed.";
}
_stopButton.Enabled = false;
_startButton.Enabled = true;
}
}
public class MyWorker : BackgroundWorker
{
protected override void OnDoWork(DoWorkEventArgs e)
{
base.OnDoWork(e);
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(500);
if (this.CancellationPending)
{
e.Cancel = true;
e.Result = false;
return;
}
}
e.Result = true;
}
}
}
If you really really don't want your method to exit, I'd suggest putting a flag like an AutoResetEvent on a derived BackgroundWorker, then override OnRunWorkerCompleted to set the flag. It's still kind of kludgy though; I'd recommend treating the cancel event like an asynchronous method and do whatever it's currently doing in the RunWorkerCompleted handler.
I'm a little late to the party here (about 4 years) but what about setting up an asynchronous thread that can handle a busy loop without locking the UI, then have the callback from that thread be the confirmation that the BackgroundWorker has finished cancelling?
Something like this:
class Test : Form
{
private BackgroundWorker MyWorker = new BackgroundWorker();
public Test() {
MyWorker.DoWork += new DoWorkEventHandler(MyWorker_DoWork);
}
void MyWorker_DoWork(object sender, DoWorkEventArgs e) {
for (int i = 0; i < 100; i++) {
//Do stuff here
System.Threading.Thread.Sleep((new Random()).Next(0, 1000)); //WARN: Artificial latency here
if (MyWorker.CancellationPending) { return; } //Bail out if MyWorker is cancelled
}
}
public void CancelWorker() {
if (MyWorker != null && MyWorker.IsBusy) {
MyWorker.CancelAsync();
System.Threading.ThreadStart WaitThread = new System.Threading.ThreadStart(delegate() {
while (MyWorker.IsBusy) {
System.Threading.Thread.Sleep(100);
}
});
WaitThread.BeginInvoke(a => {
Invoke((MethodInvoker)delegate() { //Invoke your StuffAfterCancellation call back onto the UI thread
StuffAfterCancellation();
});
}, null);
} else {
StuffAfterCancellation();
}
}
private void StuffAfterCancellation() {
//Things to do after MyWorker is cancelled
}
}
In essence what this does is fire off another thread to run in the background that just waits in it's busy loop to see if the MyWorker has completed. Once MyWorker has finished cancelling the thread will exit and we can use it's AsyncCallback to execute whatever method we need to follow the successful cancellation - it'll work like a psuedo-event. Since this is separate from the UI thread it will not lock the UI while we wait for MyWorker to finish cancelling. If your intention really is to lock and wait for the cancel then this is useless to you, but if you just want to wait so you can start another process then this works nicely.
I know this is really late (5 years) but what you are looking for is to use a Thread and a SynchronizationContext. You are going to have to marshal UI calls back to the UI thread "by hand" rather than let the Framework do it auto-magically.
This allows you to use a Thread that you can Wait for if needs be.
Imports System.Net
Imports System.IO
Imports System.Text
Public Class Form1
Dim f As New Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
Dim l As New Label
l.Text = "Please Wait"
f.Controls.Add(l)
l.Dock = DockStyle.Fill
f.StartPosition = FormStartPosition.CenterScreen
f.FormBorderStyle = Windows.Forms.FormBorderStyle.None
While BackgroundWorker1.IsBusy
f.ShowDialog()
End While
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim i As Integer
For i = 1 To 5
Threading.Thread.Sleep(5000)
BackgroundWorker1.ReportProgress((i / 5) * 100)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Text = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
f.Close()
End Sub
End Class
Fredrik Kalseth's solution to this problem is the best I've found so far. Other solutions use Application.DoEvent() that can cause problems or simply don't work. Let me cast his solution into a reusable class. Since BackgroundWorker is not sealed, we can derive our class from it:
public class BackgroundWorkerEx : BackgroundWorker
{
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
private bool _resetting, _started;
private object _lockObject = new object();
public void CancelSync()
{
bool doReset = false;
lock (_lockObject) {
if (_started && !_resetting) {
_resetting = true;
doReset = true;
}
}
if (doReset) {
CancelAsync();
_resetEvent.WaitOne();
lock (_lockObject) {
_started = false;
_resetting = false;
}
}
}
protected override void OnDoWork(DoWorkEventArgs e)
{
lock (_lockObject) {
_resetting = false;
_started = true;
_resetEvent.Reset();
}
try {
base.OnDoWork(e);
} finally {
_resetEvent.Set();
}
}
}
With flags and proper locking, we make sure that _resetEvent.WaitOne() really gets only called if some work has been started, otherwise _resetEvent.Set(); might never been called!
The try-finally ensures that _resetEvent.Set(); will be called, even if an exception should occur in our DoWork-handler. Otherwise the application could freeze forever when calling CancelSync!
We would use it like this:
BackgroundWorkerEx _worker;
void StartWork()
{
StopWork();
_worker = new BackgroundWorkerEx {
WorkerSupportsCancellation = true,
WorkerReportsProgress = true
};
_worker.DoWork += Worker_DoWork;
_worker.ProgressChanged += Worker_ProgressChanged;
}
void StopWork()
{
if (_worker != null) {
_worker.CancelSync(); // Use our new method.
}
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 20; i++) {
if (worker.CancellationPending) {
e.Cancel = true;
break;
} else {
// Simulate a time consuming operation.
System.Threading.Thread.Sleep(500);
worker.ReportProgress(5 * i);
}
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressLabel.Text = e.ProgressPercentage.ToString() + "%";
}
You can also add a handler to the RunWorkerCompleted event as shown here:
BackgroundWorker Class (Microsoft documentation).
Just wanna say I came here because I need a background worker to wait while I was running an async process while in a loop, my fix was way easier than all this other stuff^^
foreach(DataRow rw in dt.Rows)
{
//loop code
while(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
Just figured I'd share because this is where I ended up while searching for a solution. Also, this is my first post on stack overflow so if its bad or anything I'd love critics! :)
Closing the form closes my open logfile. My background worker writes that logfile, so I can't let MainWin_FormClosing() finish until my background worker terminates. If I don't wait for my background worker to terminate, exceptions happen.
Why is this so hard?
A simple Thread.Sleep(1500) works, but it delays shutdown (if too long), or causes exceptions (if too short).
To shut down right after the background worker terminates, just use a variable. This is working for me:
private volatile bool bwRunning = false;
...
private void MainWin_FormClosing(Object sender, FormClosingEventArgs e)
{
... // Clean house as-needed.
bwInstance.CancelAsync(); // Flag background worker to stop.
while (bwRunning)
Thread.Sleep(100); // Wait for background worker to stop.
} // (The form really gets closed now.)
...
private void bwBody(object sender, DoWorkEventArgs e)
{
bwRunning = true;
BackgroundWorker bw = sender as BackgroundWorker;
... // Set up (open logfile, etc.)
for (; ; ) // infinite loop
{
...
if (bw.CancellationPending) break;
...
}
... // Tear down (close logfile, etc.)
bwRunning = false;
} // (bwInstance dies now.)
You can piggy back off of the RunWorkerCompleted event. Even if you've already added an event handler for _worker, you can add another an they will execute in the order in which they were added.
public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
{
// do whatever you want to do when the cancel completes in here!
});
_worker.CancelAsync();
}
}
this could be useful if you have multiple reasons why a cancel may occur, making the logic of a single RunWorkerCompleted handler more complicated than you want. For instance, cancelling when a user tries to close the form:
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_worker != null)
{
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) => this.Close());
_worker.CancelAsync();
e.Cancel = true;
}
}
I use async method and await to wait for the worker finishing its job:
public async Task StopAsync()
{
_worker.CancelAsync();
while (_isBusy)
await Task.Delay(1);
}
and in DoWork method:
public async Task DoWork()
{
_isBusy = true;
while (!_worker.CancellationPending)
{
// Do something.
}
_isBusy = false;
}
You may also encapsulate the while loop in DoWork with try ... catch to set _isBusy is false on exception. Or, simply check _worker.IsBusy in the StopAsync while loop.
Here is an example of full implementation:
class MyBackgroundWorker
{
private BackgroundWorker _worker;
private bool _isBusy;
public void Start()
{
if (_isBusy)
throw new InvalidOperationException("Cannot start as a background worker is already running.");
InitialiseWorker();
_worker.RunWorkerAsync();
}
public async Task StopAsync()
{
if (!_isBusy)
throw new InvalidOperationException("Cannot stop as there is no running background worker.");
_worker.CancelAsync();
while (_isBusy)
await Task.Delay(1);
_worker.Dispose();
}
private void InitialiseWorker()
{
_worker = new BackgroundWorker
{
WorkerSupportsCancellation = true
};
_worker.DoWork += WorkerDoWork;
}
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
_isBusy = true;
try
{
while (!_worker.CancellationPending)
{
// Do something.
}
}
catch
{
_isBusy = false;
throw;
}
_isBusy = false;
}
}
To stop the worker and wait for it runs to the end:
await myBackgroundWorker.StopAsync();
The problems with this method are:
You have to use async methods all the way.
await Task.Delay is inaccurate. On my PC, Task.Delay(1) actually waits ~20ms.
oh man, some of these have gotten ridiculously complex. all you need to do is check the BackgroundWorker.CancellationPending property inside the DoWork handler. you can check it at any time. once it's pending, set e.Cancel = True and bail from the method.
// method here
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = (sender as BackgroundWorker);
// do stuff
if(bw.CancellationPending)
{
e.Cancel = True;
return;
}
// do other stuff
}

Categories

Resources