Manual stop debugging with backgroundworker - c#

I am writing a WPF C# project with use of BackgroundWorker (a popup window with progress bar).
I start debugging (F5 key) to check my program. After the BackgroundWorker is completed and the popup window is closed, closing the MainWindow does not automatically stop the debugging process. I have to manually hit Shift+F5 to stop the debugging.
I thought BackgroundWorker should have taken care of the Thread automatically. But anyhow, I still call backgroundworker.Dispose() and backgroundworker.CancelAsync() in the RunWorkerCompleted method. And yet, on the closing of the popup window and completion of the BackgroundWorker, I still have to manually do a Shift+F5 to stop debugging.
What is going on in the background that avoid the program from stop debug automatically?
How can I find out?
NOTE: I have made sure the backgroundworker is finished DoWork and completed before I close it. With the popup Window and the BackgroundWorker, it stop debugging automatically the moment I close the Main Window.
[EDIT with codes]
public partial class MainWindow : Window
{
BackgroundWorker backgroundworker1 = new BackgroundWorker();
PopUp pop1 = new PopUp();
public MainWindow()
{
InitializeComponent();
backgroundworker1.DoWork += BackgroundWorker_DoWork;
backgroundworker1.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
backgroundworker1.WorkerReportsProgress = true;
backgroundworker1.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundworker1.WorkerSupportsCancellation = true;
}
private void startBtn_Click(object sender, RoutedEventArgs e)
{
pop1 = new PopUp();
int iteration = 0;
if (int.TryParse(iterationTb1.Text, out iteration))
{
pop1.Show();
backgroundworker1.Dispose();
backgroundworker1.RunWorkerAsync(iteration);
outputTb1.Text = "running...";
}
}
private void cancelBtn_Click(object sender, RoutedEventArgs e)
{
pop1.Close();
backgroundworker1.CancelAsync();
}
public static int DoSlowProcess(int iterations, BackgroundWorker worker, DoWorkEventArgs e)
{
int result = 0;
for (int i = 0; i <= iterations; i++)
{
if (worker != null)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return result;
}
if (worker.WorkerReportsProgress)
{
int percentComplete = (int)((float)i / (float)iterations * 100);
worker.ReportProgress(percentComplete);
}
}
Thread.Sleep(100);
result = i;
}
return result;
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var bgw = sender as BackgroundWorker;
e.Result = DoSlowProcess((int)e.Argument, bgw, e);
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
outputTb1.Text = "Canceled";
}
else
{
outputTb1.Text = e.Result.ToString();
backgroundworker1.CancelAsync();
backgroundworker1.Dispose();
pop1.Close();
pop1.progressBar1.Value = 0;
}
}
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pop1.progressBar1.Value = e.ProgressPercentage;
pop1.progressLb1.Content = e.ProgressPercentage.ToString();
}
}

OK, I could reproduce your problem and also found the cause.
Change this line:
// PopUp pop1 = new PopUp(); <-- this never-used Win was blocking your close-down.
PopUp pop1 = null;
Because you also have
pop1 = new PopUp();
int iteration = 0;
Creating objects just to initialize a var and later overwriting it is always an anti-pattern. In this case it is actually harmful because you create a Window but never Show() or Close() it.
Note that the Backgroundworker is not involved. It couldn't be, it uses the ThreadPool and that means background Threads. You can close an App with several Backgroundworkers running w/o a problem.

Related

How do I keep a BackgroundWorker from blocking the UI thread?

In my XML editor I want to be able to open multiple files at once using an index file. Obviously, depending on the amount of files, this can take a bit of time and I want to use a progress bar to notify the user that the programm is still loading and doing something.
From what I have researched the way to keep the UI progress bar updated is using a BackgroundWorker.
public MainWindow()
{
InitializeComponent();
tabList = new ObservableCollection<FileTab>();
tabControl.ItemsSource = tabList;
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.WorkerReportsProgress = true;
}
(...)
private void OpenProjectButtonClick(object sender, RoutedEventArgs e)
{
openingProgressBar.Value = 0;
openingProgressBar.Visibility = System.Windows.Visibility.Visible;
backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
int i = 0;
foreach (IndexFile file in indexManager.fileList)
{
this.Dispatcher.Invoke((Action)(() =>
{
tabList.Add(new FileTab(file.filePath));
}));
i++;
Console.WriteLine("-(DoWork)->" + i);
double percentage = (Convert.ToDouble(i) / Convert.ToDouble(indexManager.fileList.Count)) * 100;
Console.WriteLine("-(DoWork.percentage)-> "+ percentage);
backgroundWorker.ReportProgress((int)percentage);
}
}
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
openingProgressBar.Value = e.ProgressPercentage;
Console.WriteLine("-(ProgressChanged)->" + openingProgressBar.Value);
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
openingProgressBar.Visibility = System.Windows.Visibility.Collapsed;
backgroundWorker.Dispose();
Console.WriteLine("-(RunWorkerComplete)-> Done");
}
Since I'm accessing the tablist in the DoWork-Method I wrap that call in the Dispathcer.Invoke. In this form the code kind of does what I want. It makes the collapsed progressBar visible and updates it every once in a while. Sadly it doesn't update the percentage after every file loaded. From what I can see in the console, the ProgressChanged execution lags behind the DoWork. From my understanding it is called in every iteration of the loop though. And even if it fires the UI doesn't always respond to that.
So my question is: Am I still blocking the UI thread somehow and how could I fix it?
The Problem is that
you are do a coupling between UI and BackgroundWorker
The Solution
return on ReportProgress your FileTab object
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
int i = 0;
foreach (IndexFile file in indexManager.fileList)
{
i++;
Console.WriteLine("-(DoWork)->" + i);
double percentage = (Convert.ToDouble(i) / Convert.ToDouble(indexManager.fileList.Count)) * 100;
Console.WriteLine("-(DoWork.percentage)-> "+ percentage);
backgroundWorker.ReportProgress((int)percentage,new FileTab(file.filePath));
}
}
then add your FileTab object in your backgroundWorker_ProgressChanged to the tabList
Try to move the reporting progress operation into the dispatcher's operations:
foreach (IndexFile file in indexManager.fileList)
{
this.Dispatcher.Invoke((Action)(() =>
{
tabList.Add(new FileTab(file.filePath));
Console.WriteLine("-(DoWork)->" + i);
double percentage = (Convert.ToDouble(i) / Convert.ToDouble(indexManager.fileList.Count)) * 100;
Console.WriteLine("-(DoWork.percentage)-> "+ percentage);
backgroundWorker.ReportProgress((int)percentage);
}));
i++;
}
It's possible that dispatcher runs in another thread...

How to make a progressbar run in a different thread in C#

I want to create a basic multi-thread application using a progress bar. Meaning that this progress bar will run on a different thread while the main thread is busy in the large process it is doing. I've seen a lot of tutorials about it. But the thing that they are multi-threading is the one that doing the large process. The progress bar in the other form is just showing a simple progress bar that runs and complete using a timer.
This is the code I have now.
For the thread:
public void thread()
{
Form6 for6 = new Form6();
for6.Show();
}
TH1 = new Thread(thread);
TH1.Start();
For the progress bar (Code inside form 6)
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Increment(+1);
if (progressBar1.Value == 99)
{
this.Close();
}
}
private void Form6_Load(object sender, EventArgs e)
{
timer1.Start();
}
My problem is the thread in here doesn't run the Form6. Is there any way for me to do this?
Instead of using main thread for large processing you can use the Background worker for all the processing.
Here's a simple example to do it.
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label1.Text = "";
label2.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int total = 57; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
bgw.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
}
Instead of the ProgressBar, you should really move your long-running, non-UI code into a separate thread. The standard and easier way of doing this in WinForms is to use BackgroundWorker component, which can raise ProgressChanged event where you can update your UI. Important to note that ProgressChanged event is raised on the UI thread, not on the worker thread, so you don't even need to use Invoke() to perform UI operations (such as updating your ProgressBar).
you must use Control.Invoke for avoid cross-threading problem,but I prefer use BackgroundWorker for resolve it, create Form6 on a _field and use progressbar in ProgressChanged event for more information see this page
public void thread()
{
Form6 for6=null;
Application.OpenForms[0].Control.Invoke(delegate{
for6 = new Form6();
for6.Show();
});
}

ProgressBar while finding a file

Hi I am trying to show a progress bar while in background the code is looping till it finds a file with specific name.
I have written following code for that but the progress bar values doesn't change.
What should I change in the code below?
public partial class Form1 : Form
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
public Form1()
{
InitializeComponent();
progressBar1.Visible = false;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(backgroundWorker1_WorkDone);
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
progressBar1.Visible = true;
}
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
while (!File.Exists(#"C:\Users\Test.txt"))
{
continue;
}
}
}
void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
void backgroundWorker1_WorkDone(object sender,
RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
}
}
The continue in your code will simply continue to the next iteration of the while(true) loop. It won't go back up to the for loop as you expect - it just keeps looping in there over and over again. If it wasn't a background worker, it'd hang your entire program. Since it is, it just hangs that thread. I expect that one CPU core stays at 100% while this is running.
That being said, while the goal here is admirable, there's no good way to accomplish it. Even if you fix the infinite loop, your progress bar will either "finish" at a low percentage (1%, 2%, 3%, done) or go up to 100, then stop updating, but without the file yet existing.

Async Behaviour

I have the following code to update the progress bar in async fashion and i notice
its async behaviour through the call to MessageBox.In this case it works perfectly
but when i give a sleep of 1s(1000) the MessageBox doesnot pops up and the the complete progress bar fills at once.
Kindly tell why this is happening.
private void button1_Click(object sender, EventArgs e)
{
Update_Async async = new Update_Async(Update_Async_method);
progressBar1.BeginInvoke(async,10);
MessageBox.Show("Updation In Progress");
}
public void Update_Async_method(int a)
{
this.progressBar1.Maximum = a;
for (int i = 1; i <= a; i++)
{
progressBar1.Value = a;
Thread.Sleep(10);
//Thread.Sleep(1000);
}
}
Try Update_Async.BeginInvoke(async, 10) instead if you want the delegate to run asynchrnously but, you'll have to cross thread checking on the update to the progress bar.
In response to your comment, very similar to what you are doing already,
void UpdatingFunction(int value)
{
if (this.progressBar.InvokeRequired)
{
this.progressBar.BeginInvoke(UpdatingFunction, value);
return;
}
// Invoke not required, work on progressbar.
}
This also explains what the Invoke methods on controls are for.
Delegate.BeginInvoke will run a method in a thread once and then dispose it. It is a poor choice if you want to repeatedly do some work in a thread and return intermediate results. If that is what you want, you should use BackgroundWorker. Highly abbreviated snippet:
BackgroundWorker bw;
YourFormConstructor()
{
...
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += BackgroundCalculations;
bw.ProgressChanged += ShowBackgroundProgress;
}
private void button1_Click(object sender, EventArgs e)
{
bw.RunWorkerAsync(10);
}
void ShowBackgroundProgress(object sender, ProgressChangedEventArgs e)
{
this.progressBar.Value = e.ProgressPercentage;
}
static void BackgroundCalculations(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
int max = (int)e.Argument;
for (int i = 0; i < max; i++)
{
bw.ReportProgress(i * 100 / max);
Thread.Sleep(10);
}
bw.ReportProgress(100);
}
}

Why does the BackgroundWorker in WPF need Thread.Sleep to update UI controls?

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
BackgroundWorker bgWorker;
Action<int> myProgressReporter;
public Window1()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.DoWork += bgWorker_Task;
bgWorker.RunWorkerCompleted += myWorker_RunWorkerCompleted;
// hook event to method
bgWorker.ProgressChanged += bgWorker_ReportProgress;
// hook the delegate to the method
myProgressReporter = updateProgress;
bgWorker.WorkerReportsProgress = true;
}
private void myWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
object result;
result = e.Result;
MessageBox.Show(result.ToString());
progressBar1.Value = 0;
button1.IsEnabled = true;
}
private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e)
{
System.Windows.Threading.Dispatcher disp = button1.Dispatcher;
disp.BeginInvoke(myProgressReporter,e.ProgressPercentage);
//Dispatcher.BeginInvoke(myProgressReporter, DispatcherPriority.Normal, e.ProgressPercentage);
}
private void updateProgress(int progressPercentage)
{
progressBar1.Value = progressPercentage;
}
private void bgWorker_Task(Object sender, DoWorkEventArgs e)
{
int total = 1000;
for (int i = 1; i <= total; i++)
{
if (bgWorker.WorkerReportsProgress)
{
int p = (int)(((float)i / (float)total) * 100);
bgWorker.ReportProgress(p);
}
Thread.Sleep(1); // Without Thread.Sleep(x) the main thread freezes or gives stackoverflow exception,
}
e.Result = "Completed";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if(!bgWorker.IsBusy)
bgWorker.RunWorkerAsync("This is a background process");
button1.IsEnabled = false;
}
}
}
Because in your (artificial) scenario you pump 1000 request-for-update to the main thread.
It gets no time to do an idle loop (necessary to do a screen update).
But (thanks to TerrorAustralis), you should start with merging your bgWorker_ReportProgress and myProgressReporter methods. You are now synchronizing twice, a possible cause of stackoverflow. Dispatching the UpdateProgress events is one of the main features of the Backgroundworker:
private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e)
{
//System.Windows.Threading.Dispatcher disp = button1.Dispatcher;
//disp.BeginInvoke(myProgressReporter,e.ProgressPercentage);
progressBar1.Value = progressPercentage; // safe because we're on the main Thread here
}
Posibility:
Dispatcher.BeginInvoke() is an Asynchronous operation. Since this is the case, you are able to try to hit it again before it completes its operation. To see if this is the problem, try Dispatcher.Invoke() which is Synchronous
As a possible workaround, if you just want to update the progress bar, the backgroundWorker ProgressChanged event could do this without the use of an explicit dispatcher.

Categories

Resources