C# BackgroundWorker - how should i get rid of DoEvents - c#

I'm trying to figure out the best way to handle a backgroundworker that is triggered off radio button clicks. I created a very simple form with 3 radio buttons and a label. Each of the radio buttons share the same event radioButton_CheckedChanged. If the event completes then I update the label to "Complete". If you click another radio button before the event completes then update label to Cancelled. Below is the code i have written in this quick example. Although the application tends to run as expected my concern is the use of Application.DoEvents. What are my alternatives to this. For obvious reasons i can't sleep while IsBusy. Am I going about this all wrong or is there a better way to do this?
Thanks, poco
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
while (backgroundWorker1.IsBusy)
Application.DoEvents();
}
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i < 100 && !worker.CancellationPending; ++i)
Thread.Sleep(1);
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
label1.Text = "Canceled";
else
label1.Text = "Complete";
}

You should move the code that must run when the BackgroundWorker completes into the RunWorkerCompleted hander. In pseudo-code:
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
// ...
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
addJobToQueue(); // Don't wait here, just store what needs to be executed.
} else {
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled) {
label1.Text = "Canceled";
}
else {
label1.Text = "Complete";
}
// We've finished! See if there is more to do...
if (thereIsAnotherJobInTheQueue())
{
startAnotherBackgroundWorkerTask();
}
}

DoEvents is not supposed to be taken so casually. There are better ways. One of the very nice ones is described here in SO. This answer is probably best for you.
Hence your solution becomes:
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i < 100 && !worker.CancellationPending; ++i)
Thread.Sleep(1);
if (worker.CancellationPending)
{
e.Cancel = true;
}
_resetEvent.Set();
}

Related

Events not happening in order

I am creating a WinForms application in C#. When I click a button, a certain flow of events is supposed to transpire:
Click Button
Show label1
Show label2
Call function to parse a string the user entered before (this can take awhile depending on the string)
Show listBox1 and progressBar1
backgroundWorker1.RunWorkerAsync
backgroundWorker1_DoWork() does something x number of times and reports progress each time
backgroundWorker1_ProgressChanged() updates progressBar1 and adds an item to listBox1
backgroundWorker1_RunWorkCompleted() shows a message box saying "DONE"
But that is not what actually happens. When I trace through the code and look at the form it has several problems.
label1 and label2 do not actually appear until after the parsing is done.
progressBar1 only sometimes gets updated as ProgressChanged gets called. Other times it will wait until after "DONE" is printed and update all at once.
Each time progressChange() gets called the vertical scroll bar on listBox1 gets smaller so I can tell Items are being added, but the text of the Items does not appear until after "DONE" is printed.
I am new to using backgroundWorker, so it's possible I just don't understand how it is supposed to function. But the delay of showing the labels I just don't understand at all. There are no errors when I trace through the code and the lines appear to be executed in the correct order.
Does anyone have ideas about what could be causing these issues? I would appreciate any help or advice. I'd rather not post my code, just because there is kind of a lot, but if anyone needs it to better understand, just lmk.
EDIT: Here is the code.
private void button1_Click(object sender, EventArgs e){
label1.Show();
label2.Show();
String errMsg = parseString();
if (errMsg == ""){
listBox1.Items.Clear();
listBox1.Show();
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
progressBar1.Show();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(1, "Updating Devices");
for (int i = 0; i < 100; i++)
{
//todo: do stuff
//update progress
backgroundWorker1.ReportProgress(i, "Device:" + i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
listBox1.Items.Add(e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("DONE");
}
Thanks to #HansPassant and #mjwills for their comments. They led me on the right track and made this solution possible.
In the end I decided to do two background workers to solve the issue of label1 and label2 not appearing until after the parsing was done. I use the first one to do the parsing and the second one to do the "do stuff" section. In the code you will see I had to use Invoke to edit the labels since that part now existed on a different thread.
I also realized that the "do stuff" before calling ProgressChanged is not immediate. I've been developing in pieces and hadn't yet implemented that code, but I know it will take at least 3 seconds for those actions to complete (partly because pinging is involved). So for now I have put a Sleep(3000) call in that loop to simulate how it will actually behave. This solved the weird progressbar1 and listbox1 behavior which was caused by eating up all the memory.
Here is how the code turned out:
private void button1_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
String errMsg = parseString();
if (errMsg == "")
{
if (listBox1.InvokeRequired)
{
listBox1.Invoke(new MethodInvoker(delegate
{
listBox1.Items.Clear();
listBox1.Show();
}));
}
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new MethodInvoker(delegate
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
progressBar1.Show();
}));
}
if (backgroundWorker2.IsBusy != true)
{
backgroundWorker2.RunWorkerAsync();
}
}
else
{
MessageBox.Show(errMsg);
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker2.ReportProgress(1, "Updating Devices");
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(3000);
//do stuff
backgroundWorker2.ReportProgress(i, "Device:" + i);
}
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new MethodInvoker(delegate
{
progressBar1.Value = e.ProgressPercentage;
}));
}
if (listBox1.InvokeRequired)
{
listBox1.Invoke(new MethodInvoker(delegate
{
listBox1.Items.Add(e.UserState);
}));
}
}
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("DONE");
}

C# - Break Loop from another button

In my program i'm starting for loop using button, I want to break this for loop using another button.
For example:
private void button1_Click(object sender, EventArgs e)
{
for( int i = 0; i < var; i++)
{
//doing something
}
}
And using second button break loop,
private void button2_Click(object sender, EventArgs e)
{
//breaking loop;
}
Need help :)
Set a flag in button2_Click() method and check it in the button1_Click()'s loop.
In order to process Windows events and allow button2_Click() handle to run while iterating, add Application.DoEvents() in your loop:
bool breakLoop = false;
private void button1_Click(object sender, EventArgs e)
{
breakLoop = false;
for( int i = 0; i < var && !breakLoop; i++)
{
//doing something
Application.DoEvents();
}
}
private void button2_Click(object sender, EventArgs e)
{
breakLoop = true;
}
You cannot do that, because the loop in button1_Click event handler will be holding the UI thread. Your user interface will not respond to any event, showing hourglass icon, until the loop is over. This means that button2_Click cannot be entered until button1_Click has completed.
You need to replace the long-running loop from the event handler with something that runs outside the UI thread. For example, you can use Tasks, which can be cancelled using CancellationToken (related Q&A).
Arguably it would be better to use threads and cancellation tokens in some form, rather than the Application.DoEvents(). Something like this:
private CancellationTokenSource loopCanceller = new CancellationTokenSource();
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
try
{
for (int i = 0; i < 100; i++)
{
this.loopCanceller.Token.ThrowIfCancellationRequested(); // exit, if cancelled
// simulating half a second of work
Thread.Sleep(500);
// UI update, Invoke needed because we are in another thread
Invoke((Action)(() => this.Text = "Iteration " + i));
}
}
catch (OperationCanceledException ex)
{
loopCanceller = new CancellationTokenSource(); // resetting the canceller
Invoke((Action)(() => this.Text = "Thread cancelled"));
}
}, loopCanceller.Token);
}
private void button2_Click(object sender, EventArgs e)
{
loopCanceller.Cancel();
}

How to use progressbar.value property at different locations of program

I need to use progressbar.value property at different locations. But the problem is, while executing it shows only maximum value given. I need to stop at 25% and 75% and after some delay, 100%. How can I overcome this problem. Thanks in Advance...
C#
namespace ProgressBarWindowForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, System.EventArgs e)
{
label1.Hide();
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
if (progressBar1.Value == 25)
{
label1.Show();
label1.Text = "Process Complete 25%";
}
progressBar1.Value = 75;
if (progressBar1.Value == 75)
{
label1.Show();
label1.Text = "Process Complete 75%";
}
}
}
}
Progressbar control name is progressBar1,
Label name is label1 and
Button name is button1
When I Clicked the Button, progressbar value is directly filling with 75%. I want to stop it at 25% and after some delay it should fill 75% and then 100%...Can anyone help..Can I use "progressBar1.value" only Once or as many times I need?
try this,Drag and drop background worker in windows form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void button1_Click(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
if (label1.InvokeRequired)
{
label1.Invoke(new MethodInvoker(delegate
{
label1.Show();
label1.Text = "Process Complete " + progressBar1.Value + "%";
}));
}
if (progressBar1.Value == 25 || progressBar1.Value == 75)
{
System.Threading.Thread.Sleep(1000);
}
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}
Use a Timer to update the progress bar after a delay:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer.Tick += Timer_Tick;
timer.Interval = 1000; // delay: 1000 milliseconds
}
Timer timer = new Timer();
private void Timer_Tick(object sender, EventArgs e)
{
if (progressBar1.Value == 100)
{
timer.Stop();
return;
}
progressBar1.Value += 25;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
timer.Start();
}
}
Its simple to update progressBar values in button click, you can initialize the properties in the page load or else use the designer, in page load it would be like the following:
private int ProgressPercentage = 10;
public void Form1_Load(object sender, System.EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
}
So the initialization completed, now you can code the button click like the following, through which you can update the progress bar in every button click:
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
}
If you want the update to be happens automatically in a particular interval means you can make use of a timer and enable the timer in the button click. Here you can find a similar thread which can be used to implement timer to your scene.
Update as per your comment, calling a delay will not be a best practice, you can make use a timer here as like the following:
System.Windows.Forms.Timer proTimer = new System.Windows.Forms.Timer();
private void Form1_Load(object sender, EventArgs e)
{
proTimer.Interval = 1000;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
proTimer.Tick += new EventHandler(proTimer_Tick);
}
private void button1_Click(object sender, EventArgs e)
{
proTimer.Enabled = true;
proTimer.Start();
}
// Timer event
void proTimer_Tick(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
if (progressBar1.Value == 100)
{
proTimer.Stop();
proTimer.Enbled = false;
}
}
You need to add a delay inbetween the changes. As of now, the button advance the bar to 25, sets the label, then advances the bar to 75 without pausing.
System.Threading.Thread.Sleep(n); will sleep n milliseconds, which you will need after the statement setting the 25 percent marker.
EDIT
If you want it the value to only progress on a button click, you will need to check the value of the progress bar before you advance it.
In pseudo code, something like:
onclick() {
if (progress == 0) {
progress = 25
label = the25MarkText
} else if (progress == 25) {
progress = 75
label = the75MarkText
}
}

progress bar in background worker get argument which being updated in the main thread c# wpf

I have the main thread which is wizard in WPF.
after user finished set the properties of the wizard, it processing data.
It takes a few seconds and I would like to raise a progress bar which report on the progress.
Hence, I set always on the main thread variable call currentStep.
I have totally thresholdStep steps which equals to 12.
So I want that the progress bar will work as a thread but it will also will be connected to the main thread by using currentStep variable.
So, I used by background worker like this:
public partial class MessageWithProgressBar : Window
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public MessageWithProgressBar()
{
InitializeComponent();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += ProgressChanged;
backgroundWorker.DoWork += DoWork;
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
}
private void DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
int i = (int)e.Argument;
backgroundWorker.ReportProgress((int)Math.Floor((decimal)(8*i)));
if (i > GeneralProperties.General.thresholdStep)
backgroundWorker.ReportProgress(100);
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.Value = e.ProgressPercentage;
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
WindowMsg msg = new WindowMsg();
msg.Show();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (backgroundWorker.IsBusy == false)
backgroundWorker.RunWorkerAsync(GeneralProperties.General.currentStep);
}
}
In addition, I called the background worker from the main thread as below:
MessageWithProgressBar progress = new MessageWithProgressBar();
progress.Show();
What acutally happens is that DoWork called only once with currentStep = 1 and it don't updates in relation to the main thread which also updated currentStep dependents on it's progress.
Any ideas how to solve it?
Thanks!
Change your DoWork method like below:
private void DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
int i = (int)e.Argument;
do
{
i = GeneralProperties.General.currentStep;
backgroundWorker.ReportProgress((int)Math.Floor((decimal)(8 * i)));
if (i > GeneralProperties.General.thresholdStep)
backgroundWorker.ReportProgress(100);
}
while (i < GeneralProperties.General.thresholdStep);
}
Just make sure your are not getting thread synchronization problem with GeneralProperties.General object, if you are then use lock when accessing the object.
UPDATE:
For update problem:
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
{
progress.Value = e.ProgressPercentage;
}), null);
}

BackgroundWorker doesn't report progress when trying to send a loop of sms

I'm having a problem in using the BackgroundWorker while using a loop in sending sms, I want to return its progress in ProgressBar but I'm having an error "it doesn't report progress"
private void btnSend_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
comm.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int l = 0; l < 4; l++)
{
backgroundWorker1.ReportProgress(l);
i++;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
You need to set the WorkerReportsProgress property of the background worker to true. This can be done in the designer via the Properties window.

Categories

Resources