Progressbar does not move (WinForms, .Net and BackgroundWorker) - c#

Introduction
I am trying to make a WinForms app using .Net.
I am using tutorial from here wich shows BackgroundWorker and ProgressBar integration.
I added ProgressBar and BackgroundWorker controls to the form.
The names are the same as in example. Additionaly, i set WorkerReportProgress property to True for BackgroundWorker. No errors are shown and project compiles sucessfully...
Problem
The problem is - progressbar does not move.
And yet, it moves when clicked manually... progressBar1.PerformStep();.
What am i missing?
Code
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
BackgroundWorker1.RunWorkerAsync();
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 500 milliseconds.
Thread.Sleep(500);
// Report progress.
BackgroundWorker1.ReportProgress(i);
}
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
progressBar1.PerformStep();
}
}
}
Update
Removed progressBar1.PerformStep(); from DoWork and ProgressChanged.
Still the problem persists (ProgressBar does not move).
Thank you for ideas so far, will look into it more on Monday.

After you made sure you attached the event handlers to ProgressChanged and DoWork:
Remove progressBar1.PerformStep() from DoWork event handler.
Then use just progressBar1.Value = e.ProgressPercentage; in ProgressChanged event handler.

I wrote a simple Multithreading with Progress bar code a few years back. Hope it helps you:
#region Primenumbers
private void btnPrimStart_Click(object sender, EventArgs e)
{
if (!bgwPrim.IsBusy)
{
//Prepare ProgressBar and Textbox
int temp = (int)nudPrim.Value;
pgbPrim.Maximum = temp;
tbPrim.Text = "";
//Start processing
bgwPrim.RunWorkerAsync(temp);
}
}
private void btnPrimCancel_Click(object sender, EventArgs e)
{
if (bgwPrim.IsBusy)
{
bgwPrim.CancelAsync();
}
}
private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
{
int highestToCheck = (int)e.Argument;
//Get a reference to the BackgroundWorker running this code
//for Progress Updates and Cancelation checking
BackgroundWorker thisWorker = (BackgroundWorker)sender;
//Create the list that stores the results and is returned by DoWork
List<int> Primes = new List<int>();
//Check all uneven numbers between 1 and whatever the user choose as upper limit
for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
{
//Report progress
thisWorker.ReportProgress(PrimeCandidate);
bool isNoPrime = false;
//Check if the Cancelation was requested during the last loop
if (thisWorker.CancellationPending)
{
//Tell the Backgroundworker you are canceling and exit the for-loop
e.Cancel = true;
break;
}
//Determin if this is a Prime Number
for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
{
if (PrimeCandidate % j == 0)
isNoPrime = true;
}
if (!isNoPrime)
Primes.Add(PrimeCandidate);
}
//Tell the progress bar you are finished
thisWorker.ReportProgress(highestToCheck);
//Save Return Value
e.Result = Primes.ToArray();
}
private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbPrim.Value = e.ProgressPercentage;
}
private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pgbPrim.Value = pgbPrim.Maximum;
this.Refresh();
if (!e.Cancelled && e.Error == null)
{
//Show the Result
int[] Primes = (int[])e.Result;
StringBuilder sbOutput = new StringBuilder();
foreach (int Prim in Primes)
{
sbOutput.Append(Prim.ToString() + Environment.NewLine);
}
tbPrim.Text = sbOutput.ToString();
}
else
{
tbPrim.Text = "Operation canceled by user or Exception";
}
}
#endregion
Normally when writing a UI Element from a Alterante Thread, you have to use Invoke. BackgroundWorker is nice and Invoking the "ReportProgress" and "RunWorkerCompleted" Events on the thread that created it (wich should be the GUI thread) so you do not have to deal with that part of Multithreading wonkyness yet.
It is also nice enough to catch any Exceptions that would normally escape DoWork and be swallowed, exposing them to you in the Completed Event Args. Swallowing Exceptions is a huge issue with Multithreading.
The core issue is, that your loop breaks due to a Exception. Calling progressBar1.PerformStep(); inside the DoWork Event has to throw a "CrossThreadException". The BackgroudnWorker finishes (due to an exception) instantly. The RunWorker completed event is triggered when i was just the initial value.

Related

Why can I not recursively call a Worker_DoWork function?

I have a tcp server and client in c# using Sytem.Net.Sockets. My worker function is as following
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
byte[] buffer = new byte[1];
socket.Receive(buffer);
chatTextBox.Text = buffer[0].ToString();
}
I'm calling this after the server is created, as soon as it receives a message from the client it writes it on the screen and stops. My issue is I want it at the end to call itself again so it waits for another message to display. If I just add worker.RunWorkerAsync(); at the bottom it doesn't work, however if I just call it from another button it works and receives and writes the message.
The BackgroundWorker "wraps" around a Thread and helps you with all the plumbing. It is a horribly dated approach to Multitasking taht you should not use in producive code anymore. However it is also the best "Training Wheels" for Multitasking I know off.
Your fundamental approach is flawed. The BGW not allowing that is really just it helping you learn the things you need to learn. A list of mistakes in your code:
you are accessing a GUI element directly in DoWork. Do not do that. Only write the UI in ReportProgress and RunWorker completed Events. This is a general Multithreading rule, that is helped by teh BGW's design.
you are trying to restart the thread, before it has finished. If you wanted to restart it, RunWorkerCompleted would be the right place
however more sensible would be for the core of the BackgroundWorker to be a semi-infinite loop. Something that runs until canceled. Normally handing out inforamtion with reporting is not a good idea, but in this case it is the best idea I have.
The only other thing I can give you, is my old BGW example code:
#region Primenumbers
private void btnPrimStart_Click(object sender, EventArgs e)
{
if (!bgwPrim.IsBusy)
{
//Prepare ProgressBar and Textbox
int temp = (int)nudPrim.Value;
pgbPrim.Maximum = temp;
tbPrim.Text = "";
//Start processing
bgwPrim.RunWorkerAsync(temp);
}
}
private void btnPrimCancel_Click(object sender, EventArgs e)
{
if (bgwPrim.IsBusy)
{
bgwPrim.CancelAsync();
}
}
private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
{
int highestToCheck = (int)e.Argument;
//Get a reference to the BackgroundWorker running this code
//for Progress Updates and Cancelation checking
BackgroundWorker thisWorker = (BackgroundWorker)sender;
//Create the list that stores the results and is returned by DoWork
List<int> Primes = new List<int>();
//Check all uneven numbers between 1 and whatever the user choose as upper limit
for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
{
//Report progress
thisWorker.ReportProgress(PrimeCandidate);
bool isNoPrime = false;
//Check if the Cancelation was requested during the last loop
if (thisWorker.CancellationPending)
{
//Tell the Backgroundworker you are canceling and exit the for-loop
e.Cancel = true;
break;
}
//Determin if this is a Prime Number
for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
{
if (PrimeCandidate % j == 0)
isNoPrime = true;
}
if (!isNoPrime)
Primes.Add(PrimeCandidate);
}
//Tell the progress bar you are finished
thisWorker.ReportProgress(highestToCheck);
//Save Return Value
e.Result = Primes.ToArray();
}
private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbPrim.Value = e.ProgressPercentage;
}
private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pgbPrim.Value = pgbPrim.Maximum;
this.Refresh();
if (!e.Cancelled && e.Error == null)
{
//Show the Result
int[] Primes = (int[])e.Result;
StringBuilder sbOutput = new StringBuilder();
foreach (int Prim in Primes)
{
sbOutput.Append(Prim.ToString() + Environment.NewLine);
}
tbPrim.Text = sbOutput.ToString();
}
else
{
tbPrim.Text = "Operation canceled by user or Exception";
}
}
#endregion

C# BackgroundWorker.CancelAsync() vs DoWorkEventArgs.Cancel

I want to use the RunWorkerCompletedEventArgs.Cancelled value in my BackgroundWorker completed handler, but the documentation isn't clear how how BackgroundWorker.CancelAsync() and DoWorkEventArgs.Cancel (in the background worker do work handler) will each effect it. Are they functionally the same?
For example, is this...
private void _Worker_DoWork(object sender, DoWorkEventArgs e)
{
(sender as BackgroundWorker).CancelAsync();
}
...equivalent to this?
private void _Worker_DoWork(object sender, DoWorkEventArgs e)
{
e.Cancel = true;
}
Will the latter result in subsequent evaluations of CancellationPending() to evaluate as true? Also, if the background worker is cancelled externally (i.e. myBW.CancelAsync(); outside the do work handler), will e.Cancel = false cause an evaluation of CancellationPending() to be false?
BackgroundWorker.CancelAsync() will set the value of BackgroundWorker.CancellationPending to true, so the DoEvent code can check it.
DoWorkEventArgs.Cancel is there to tell RunWorkerCompleted Event that the process was Canceled. You are not supposed to use the result of a operation that was aborted or ended in Exception. Setting DoWorkEventArgs.Cancel to true will set RunWorkerCompletedEventArgs.Canceled to true. Wich will also force RunWorkerCompletedEventArgs.Result to throw an exception if accessed.
I have some pretty old example code from when I learned Multithrading with BGW. It should help you.
#region Primenumbers
private void btnPrimStart_Click(object sender, EventArgs e)
{
if (!bgwPrim.IsBusy)
{
//Prepare ProgressBar and Textbox
int temp = (int)nudPrim.Value;
pgbPrim.Maximum = temp;
tbPrim.Text = "";
//Start processing
bgwPrim.RunWorkerAsync(temp);
}
}
private void btnPrimCancel_Click(object sender, EventArgs e)
{
if (bgwPrim.IsBusy)
{
bgwPrim.CancelAsync();
}
}
private void bgwPrim_DoWork(object sender, DoWorkEventArgs e)
{
int highestToCheck = (int)e.Argument;
//Get a reference to the BackgroundWorker running this code
//for Progress Updates and Cancelation checking
BackgroundWorker thisWorker = (BackgroundWorker)sender;
//Create the list that stores the results and is returned by DoWork
List<int> Primes = new List<int>();
//Check all uneven numbers between 1 and whatever the user choose as upper limit
for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2)
{
//Report progress
thisWorker.ReportProgress(PrimeCandidate);
bool isNoPrime = false;
//Check if the Cancelation was requested during the last loop
if (thisWorker.CancellationPending)
{
//Tell the Backgroundworker you are canceling and exit the for-loop
e.Cancel = true;
break;
}
//Determin if this is a Prime Number
for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2)
{
if (PrimeCandidate % j == 0)
isNoPrime = true;
}
if (!isNoPrime)
Primes.Add(PrimeCandidate);
}
//Tell the progress bar you are finished
thisWorker.ReportProgress(highestToCheck);
//Save Return Value
e.Result = Primes.ToArray();
}
private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbPrim.Value = e.ProgressPercentage;
}
private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pgbPrim.Value = pgbPrim.Maximum;
this.Refresh();
if (!e.Cancelled && e.Error == null)
{
//Show the Result
int[] Primes = (int[])e.Result;
StringBuilder sbOutput = new StringBuilder();
foreach (int Prim in Primes)
{
sbOutput.Append(Prim.ToString() + Environment.NewLine);
}
tbPrim.Text = sbOutput.ToString();
}
else
{
tbPrim.Text = "Operation canceled by user or Exception";
}
}
#endregion
Personally I consider the BackgroundWorker class in a GUI to be good Multitasking "Training Wheels".
No, they are not the same. The "CancelAsync()" method runs from outside of the "backgroundworker"'s code. The "CancellationPending" can be check in the "DoWork" body and "e.Cancel" is set in "DoWork" to be used in the "Completed" method.
Please see the page below for more information:
(https://www.c-sharpcorner.com/uploadfile/mahesh/backgroundworker-in-C-Sharp/)

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();
}

Progress bar not incrementing

I have the following code which read a file and also increment the progress bar while reading it, but I don't see any activity in my progressBar. Why is this?
progressBar1.Minimum = 0;
progressBar1.Maximum = (int)fileStream.Length + 1;
progressBar1.Value = 0;
using (fileStream)
{
fileStreamLength = (int)fileStream.Length + 1;
fileInBytes = new byte[fileStreamLength];
int currbyte = 0, i = 0;
var a = 0;
while (currbyte != -1)
{
currbyte = fileStream.ReadByte();
fileInBytes[i++] = (byte)currbyte;
progressBar1.Value=i;
}
}
It is incrementing but you cannot see it. It is caused by running your loop in UI thread.
Look for BackGroundWorker or async/await pattern.
User Method Invoker to update the UI...
try this...
Do all the your work in a thread and when updating the progressbar use the following lines...
For Windows Forms
this.Invoke((MethodInvoker) delegate
{
progressBar1.value=i;
});
For WPF
Dispatcher.BeginInvoke(new Action(delegate
{
progressBar1.value=i;
}));
your best option will be Background Worker.
drag and drop a BackgroundWorker from toolbox. then you have to implement 2 function: one is doing the background work, another is for reporting to UI.
using System.ComponentModel;
using System.Threading;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// begin reading your file here...
// set the progress bar value and report it to the main UI
int i = 0; // value between 0~100
backgroundWorker1.ReportProgress(i);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}

How do I use backgroundworker in this instance?

I've a question on how the backgroundworker would actually work. I'm not too sure how it would work with different methods.
So for example I have the following code (adapted from http://broadcast.oreilly.com/2010/06/understanding-c-using-backgrou.html for illustration purposes):
private void getDateTime()
{
DateTime startTime = DateTime.Now;
double value = Math.E;
while (DateTime.Now < startTime.AddMilliseconds(100))
{
value /= Math.PI;
value *= Math.Sqrt(2);
}
}
private backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for(int i=0; i <= 100; i++)
{
getDateTime();
backgroundWorker1.ReportProgress(i);
}
}
This would continually calculate the DateTime using the backgroundworker thread. Now I'm assuming that the for-loop within the backgroundworker's DoWork method would run the calculation, report the progress, and then reiterate the loop (please do correct me if I've misunderstood).
Now assuming I have another method, which parses a (presumably large) DataTable and returns another DataTable, using it in the backgroundworker would mean I'd be parsing the DataTable over and over (theoretically. again, correct me if I'm wrong)? If this is how the program would flow, is there a more efficient method to achieve the DataTable parsing without having to reiterate the loop, but still being able to use backgroundworker?
This is intended for a Windows Form, and the UI tends to freeze up when I parse the DataTable(s). I've heard that backgroundworker could help me get around the freezing of the UI, but I find it highly inefficient to have to re-parse the entire DataTable over, and over. However I'm not sure of any other way I can report progress without a for-loop either.
EDIT:
I've figured out a temporary solution. It works, but I still have no way of reporting progress.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int rows = (int)e.Argument;
int count = 0;
t3 = runComparison();
for (int i = 0; i <= rows; i++)
{
count++;
int current = count / rows;
backgroundWorker1.ReportProgress(current * 100);
}
e.Result = t3;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An unexpected error has occurred. Please try again later.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dataGridView1.DataSource = e.Result;
}
}
I'm aware my for-loop doesn't do anything. However, the "runComparison" already consumes a lot of time. As such, progress doesn't get reported until an entire run-through if it's in the for-loop. Alternatively, maybe I could use a label or messagebox instead of the progress bar. Not too sure how I'm supposed to achieve this.
Try to do this:
//make sure background worker report progress
backgroundWorker1.WorkerReportsProgress = True;
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Refresh;
//if your progressbar is on a status strip, you need to refresh the status strip instead
}
I've come up with a rather inelegant solution. But it satisfies the requirement for user-friendliness so... Whatever works :P
Thanks for all the feedback, I appreciate it.
Anyway, here's the code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(1); //to invoke ProgressChanged
t3 = runComparison(); //run intensive method
e.Result = t3; //return DataTable
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Visible = true; //display a label
textBoxProgress.Visible = true; //display the progress bar
//change the progress bar style
//the Marquee style is constantly running, so it could show users the process is working
//not too sure how to explain it, you'll have to try it out.
progressBar1.Style = ProgressBarStyle.Marquee;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An unexpected error has occurred. Please try again later.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
//reset the display and update the DataGridView
progressBar1.Visible = false;
textBoxProgress.Visible = false;
progressBar1.Style = ProgressBarStyle.Blocks;
dataGridView1.DataSource = e.Result;
}
}

Categories

Resources