BackgroundWorker - reporting progress with "sub tasks" - c#

A WinForms application with a custom control, LabelProgressBar, which has the ability to display both progress and some descriptive text and/or percentage completion. This is done by calling LabelProgressBar.statusInProgress(string message, int percentageCompletion).
One usage of this is as follows:
private void import_begin(System.Object sender, System.ComponentModel.DoWorkEventArgs args)
{
// first unpack the arguments
System.Object[] arguments = (System.Object[])args.Argument;
System.String filename = (System.String)arguments[0];
System.String why = (System.String)arguments[1];
// tasks:
// 1. read excel file and apply changes to model
// 2. gather changes and format them as XML
// 3. send request to server
// 4. commit/rollback changes
// grab the worker thread so we can report percentage progress
System.ComponentModel.BackgroundWorker worker = (System.ComponentModel.BackgroundWorker)sender;
// now do the work
#region Task1
Controller.Excel excel = new Controller.Excel(filename);
try
{
// the progress of this needs to be tracked
overall_result = excel.import_all(out modified_nodes);
}
catch (InvalidDataExcetpion invDataEx)
{
// deal with it
}
#endregion
worker.ReportProgress(25);
// complete remaining tasks...
}
The event handler for the worker reporting its progress is the following:
private void import_progress(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
Debug.WriteLine("Import percentage completion: " + e.ProgressPercentage);
labelProgressBar1.statusInProgress("Import", e.ProgressPercentage);
}
In short, the import_begin method is broken up into several "tasks". These are broken up into "subtasks". Taking the example of the import_all method:
public Command_Result import_all(out System.Collections.Generic.List<Model.Data_Node> nodes)
{
Command_Result overall_result = Command_Result.OK;
Command_Result this_result;
nodes = new System.Collections.Generic.List<Model.Data_Node>(excel.Workbook.Worksheets.Count);
Model.Data_Node destination;
// the intent is to report the progress of this particular subtask on the basis of how many worksheets have been processed in this for loop
foreach (OfficeOpenXml.ExcelWorksheet worksheet in excel.Workbook.Worksheets)
{
this_result = import_sheet(worksheet.Name, out destination);
nodes.Add(destination);
if (this_result > overall_result)
{
overall_result = this_result;
}
}
return overall_result;
}
The intent is to have this "subtask" report progress on the basis of how many sheets have been processed in the loop. Calculating a percentage for this is a trivial task, but it is not clear to me how this can be reported back to the import_begin method. When this "subtask" is completed, the overall task completion (from the POV of the import_begin method) should be 25%. Similarly for the other tasks. How can this be achieved?

import_begin don't really need to get the update, it can just call the subtasks, while also passing the BackgroundWorker, so the subtasks are responsible to directly report their progress. If "polluting" the subtasks with BackgroundWorker is unacceptable, then create a delegate to call the BackgroundWorker, so your subtasks will then call the delegate instead.
private void mainTask(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
var report = new Action<int>(i => worker.ReportProgress(i)); //the delegate
smallTask1Clean(report); //this one pass the delegate
smallTask2(worker); //this one directly call background worker
worker.ReportProgress(100);
}
void smallTask1Clean(Action<int> a)
{
for (int i = 0; i < 20; i++)
{
Thread.Sleep(500);
a(i);
}
}
void smallTask2(BackgroundWorker w)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
w.ReportProgress(i*80/5+20);
}
}
You can also insulate the subtasks from having to know their part in the larger tasks, in this case, the delegate should take two variables, the current internal progress of the subtasks and the total item it needs to process.
private void mainTask(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
var preTaskProgress = 0;
var currentTaskTotalPercentage = 0;
var smarterDelegate = new Action<int, int>((current, total) =>
{
worker.ReportProgress(preTaskProgress + (current *currentTaskTotalPercentage/total));
});
currentTaskTotalPercentage = 30; //the following task will in total progressed the main task for 30%
smallTaskClean(smarterDelegate);
preTaskProgress = currentTaskTotalPercentage; //upate the main the progress before starting the next task
currentTaskTotalPercentage = 70; //the following task will in total progressed the main task for 70%
smallTaskClean(smarterDelegate);
worker.ReportProgress(100);
}
void smallTaskClean(Action<int,int> a)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1500);
a(i,5);
}
}

Related

Progress Bar Do Work Backgroundworker C# WinForms

hope anybody can help me. My problem is the progress bar in C# WinForms. I have the following Code:
(There is a stupid calculate from an uint until a given number from a textbox and i want to show the progress while the calculate method is running)
// The stupid method which calculate
public void ueberlaufUint()
{
try
{
uint ueberlaufZahl = Convert.ToUInt32(textBox1.Text);
do
{
ueberlaufZahl++;
//Console.WriteLine(ueberlaufZahl);
} while (ueberlaufZahl <= 100);
label1.Text = "Endzahl: " + ueberlaufZahl;
}
catch (Exception)
{
MessageBox.Show("Only not negative natural numbers accepted");
}
}
// Buttonclickevent
private async void button1_Click(object sender, EventArgs e)
{
ueberlaufUint();
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
}
// DoWork
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 10000; j++)
{
ueberlaufUint();
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
The progressbar only counts few steps with no dependency (in my meaning) with the calculate method.
Very great thanks in forward, sorry for my bad english.
Just a typo. You have an extra 0 in the code:
progress.Report((j + 1) * 100 / 100000);
should be
progress.Report((j + 1) * 100 / 10000);

How to create and add controls in run time with BackgroundWorker

I don't know how to implement a method with a separate thread using the BackgroundWorker in WinForms.
I want this method (after every click on a button) to perform:
create ProgressBar (each new one under the previous one)
create Bitmap and BackgroundWorker
set color of every pixel in that Bitmap in the separate thread using BackgroundWorker
display a precentage progress on the ProgressBar
after completing: create a new form with bitmap on the background
after completing: remove the ProgressBar
My code:
List<BackgroundWorker> Workers;
List<ProgressBar> Progress;
int OperationsCount = 0;
private void ShowProgress(int n, int percent)
{
Progress[n].Value = percent;
}
private void Blend(object sender, DoWorkEventArgs e)
{
Bitmap BlendedImage = ... // creates a bitmap
for (int i = 0; i < BlendedImage.Width; i++)
{
for (int j = 0; j < BlendedImage.Height; j++)
{
... //changing colour of every pixel
}
this.Invoke(new Action(()=>ShowProgress((int)e.Argument, (int)(100 * (double)(i/BlendedImage.Width)))));
}
Form BlendedImage_Form = new Form();
BlendedImage_Form.Size = new Size(BlendedImage.Width, BlendedImage.Height);
BlendedImage_Form.BackgroundImage = BlendedImage;
BlendedImage_Form.BackgroundImageLayout = ImageLayout.Stretch;
this.Invoke(new Action(() => BlendedImage_Form.Show()));
}
private void PerformBlending_Button_Click(object sender, EventArgs e)
{
int n = OperationsCount++;
Progress.Add(new ProgressBar());
Progress[n].Size = ...
Progress[n].Location = ...
Progress[n].Maximum = 100;
this.Controls.Add(Progress[n]);
Workers.Add(new BackgroundWorker());
Workers[n].DoWork += new DoWorkEventHandler(Blend);
Workers[n].RunWorkerCompleted += (object _sender, RunWorkerCompletedEventArgs _e) =>
{
//OperationsCount--;
//Progress[n].Dispose();
//this.Controls.Remove(Progress[n]);
//Progress.RemoveAt(n);
};
Workers[n].RunWorkerAsync(n);
}
When I click the button only once then everything seems to be good but when I click the button two times then program:
creates the first ProgressBar which shows progress correctly and the new form and bitmap are displayed also correctly
creates the second ProgressBar but it doesn't show the progress at all and no form and no bitmap is displayed.
PS I'd rather use BackgroundWorker than other tools.
As per your comment here is the solution
public void DoSomething()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(()=> DoSomething()));
}
else
{
// update the ui from here, no worries
}
}
In this code, I am modifying the object on main thread. If the calls made from non-UI thread this will goes in InvokeRequired.
// From this code you given in comment
https://pastebin.com/45jQXCt9
Please try with making instance inside invoke. It should work.

Progress Bar in WPF application for long running WCF service

I have a long running WCF service and a client that consumes it via WPF. Am using a Progress Bar to notify the client of the percentage completion for a particular process (a method in WCF: I need to be able to display the percentage based on the looping counter in the service)
I have used Background Worker to display progress percentage but it does not display the progress correctly. (displays just 0 and 100 not the in between values) Everything works fine in DEBUG mode but not in RELEASE mode! (Progress bar is updated sequentially in DEBUG mode)
I tried using callbacks/wsDualHttpBinding but have some difficulty in getting this incorporated for all clients. So, had to drop this option.
working on async/await
I have googled quite a few links but nothing helps with my problem.
Please guide me on how to get the current/running value from a method that is not complete yet from a WCF service so I could populate the progress bar percentage based on this value. (in between values)
P.S: WCF service uses wsHttpBinding
sample code below:
public Progress()
{
// Start the BackgroundWorker.
myBGWorker.WorkerReportsProgress = true;
myBGWorker.WorkerSupportsCancellation = false;
myBGWorker.DoWork += myBGWorker_DoWork;
myBGWorker.ProgressChanged += myBGWorker_ProgressChanged;
}
public void ShowProgress()
{
myBGWorker.RunWorkerAsync();
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
// fetches a static value from the service
string value = _client.Progress();
int p=0;
for (int i = 1; i <= 100; i++)
{
// Report progress.
p = Convert.ToInt32(_client.Progress());
_logger.Debug("Progress5:" + p.ToString());
myBGWorker.ReportProgress(p, i);
}
}
private void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(delegate
{
progressBar1.Value = e.ProgressPercentage;
}), DispatcherPriority.ContextIdle);
}
Just to understand how it could be implemented. This is part of my working code.
.xaml file:
<ProgressBar x:Name="ProgressBarCompare" HorizontalAlignment="Left" Height="20" Margin="10,157,0,0" VerticalAlignment="Top" Width="321"/>
Function with process:
private async void btnCompare_Click(object sender, RoutedEventArgs e)
{
ProgressBarCompare.Value = 0;
lblCompare.Content = "";
List<string> list1= (List<string>)Application.Current.Properties["list1"];
List<string> list2= (List<string>)Application.Current.Properties["list2"];
List<Result> output = new List<Result>();
List<Result> passed = new List<Result>();
int topCount = emailList.Count;
int currentItem = 0;
int topBound = topCount - 1;
while (currentItem < topCount)
{
var hash = await CheckOperation(list1[currentItem]); // this line perform progress bar to be filled
var result = list2.Contains(hash);
//some operations
if (Convert.ToInt32(Math.Ceiling(100d * currentItem / topBound)) < 51)
{
Style style = this.FindResource("LabelTemplateNotFilled") as Style;
lblCompare.Style = style;
}
else
{
Style style = this.FindResource("LabelTemplateFilled") as Style;
lblCompare.Style = style;
}
ProgressBarCompare.Value = Convert.ToInt32(Math.Ceiling(100d * currentItem / topBound));
lblCompare.Content = Convert.ToInt32(Math.Ceiling(100d * currentItem / topBound)) + "%";
currentItem++;
}
lblCompare.Content = "COMPLETE";
}
and core function to that:
private async Task<string> CheckOperation(string input)
{
var result = "";
await Task.Run(() =>
{
//perform some code
});
return result;
}

Firing events in loop are not updating UI in sequence

I was trying to update status on UI for a Long Running Operating. I've created a demo form based application, task it have multiple rows, each row is having days and default values in each column of datagrid is 0, once computation file computes one iteration for one day it will update UI and set 1 for that day.
I am using threading, delegates and events to implement this and it is working as expected if I put Thread.Sleep(100) between two event calls. If I put "Thread.Sleep(100)" inside last nested for loop then it updates UI as expected but as soon as I remove it and run loop without sleep, then it skips some of the columns on UI and directly update last few/random columns, as you can see in attached image link(Image of output of my code without thread sleep) only last column is getting updated.
If I am not mistaken all the events are getting fired in sequence then they should update UI in sequence too but it's not happening and I don't know why. I don't want to do this Sleep thing because I have around 14 calls in actual application for UI status update and it will run under a loop so if It put sleep(100) then it will cost me a lot, is there any way to do it without SLEEP?
Image of output of my code without thread sleep
public class Class1 : IGenerate
{
public event MessageEventHandler OnMessageSending;
public void LongOperationMethod(BindingList<Status> _statusData)
{
if (OnMessageSending != null)
{
MessageEventArgs me = new MessageEventArgs();
/// Loop for 2-3 Weeks
for (; ; ){
/// Loop for 7 day
for (; ; )
{
/// Calculation on everyday
for (int j = 0; j != 1000; ++j)
{
// to do
}
me.weekNo = k;
me.DayNo = i;
OnMessageSending(me);
}
}
me.Message = "Process completed successfully...";
OnMessageSending(me);
}
else
{
throw new ArgumentException("Event hasn`t been rised, so we cannot continue working.");
}
}
}
**UI file:**
<pre><code>
public partial class Form1 : Form
{
BindingList<Status> _statusData = new BindingList<Status>();
delegate void StringParameterDelegate(string value);
Class1 cls = new Class1();
public Form1()
{
InitializeComponent();
labelProgress.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
for (int i = 1; i <= 2; ++i)
{
_statusData.Add(new Status { Week = "Week" + i, Day1 = 0, Day2 = 0, Day3 = 0, Day4 = 0, Day5 = 0, Day6 = 0, Day7 = 0 });
}
dataGridView1.DataSource = _statusData;
}
private void button2_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(() => StartingThread(_statusData));
t1.Start();
}
void StartingThread(BindingList<Status> _statusData)
{
IGenerate generate = new Class1();
generate.OnMessageSending += new MessageEventHandler(generate_OnMessageSending);
generate.LongOperationMethod(_statusData);
}
private void generate_OnMessageSending(MessageEventArgs e)
{
int weekNo = e.weekNo;
int dayNo = e.DayNo;
this.dataGridView1.BeginInvoke(new MethodInvoker(() => dataGridView1.Rows[e.weekNo].Cells[e.DayNo + 1].Value = 1));
this.labelProgress.BeginInvoke(new MethodInvoker(() => this.labelProgress.Text = e.Message));
}
}
</code></pre>
It looks like you are sending the same instance of MessageEventArgs every time, and just updating that one instance on the background thread. This means that your event handler on the UI thread will retrieve the exact same instance of MessageEventArgs that is being updated in the loop! By the time your UI handler gets the MessageEventArgs, its .weekNo and .DayNo properties could well have been modified by the next iteration of the loop, since they are running on separate threads.
To fix this, create a new instance of MessageEventArgs every time you call OnMessageSending().
Relevant snippet:
MessageEventArgs me = new MessageEventArgs();
me.weekNo = k;
me.DayNo = i;
OnMessageSending(me);

All threads doing same job

I want to write network address to my listview, in a range like 192.168.0.0 -192.168.255.255
and I wrote a thread application but when I run this app, all threads are trying to add addresses to listview, does it has a simple solution?
here is my code:
namespace ListNetworkComputers
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
const int step = 16777216;
int threadCount = 1;
private void frmMain_Load(object sender, EventArgs e)
{
ıpAddressControl1.Text = "192.168.0.0";
ıpAddressControl2.Text = "192.168.255.255";
}
private void btnShowPcc_Click(object sender, EventArgs e)
{
threadCount = Convert.ToInt32(nudThreads.Value);
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(new ThreadStart(getPerformance));
threads[i].Name = string.Format(i.ToString());
}
foreach (Thread t in threads)
{
t.Start();
}
}
private void getPerformance()
{
uint startIntAdress, endIntAdress;
startIntAdress = BitConverter.ToUInt32(IPAddress.Parse(ıpAddressControl1.Text).GetAddressBytes(), 0);
endIntAdress = BitConverter.ToUInt32(IPAddress.Parse(ıpAddressControl2.Text).GetAddressBytes(), 0);
for (uint i = startIntAdress; i < endIntAdress; i = i + step)
{
string ipAddress = new IPAddress(BitConverter.GetBytes(i)).ToString();
lbNetworkComputers.Items.Add(ipAddress);
}
}
}
}
And an another problem is, my step method (increaseing adresses as 16777216 ...) isnt working healthy. it goes 192.168.0.0 to 192.168.0.255 but doesnt go on after that.
Because they get same startIntAdress and endIntAdress. Split the range evenly for all threads.
It should be like this:
Thread 1 starts at 192.168.0.0 and checks 32 addresses
Thread 2 at 192.168.0.31 and checks 32,
Thread 3 at 192.168.0.63 and checks 32,
etc
Each thread is running exactly the same code as your loop over the IP addresses is inside the method passed to each thread.
You should pass different start and end addresses into each thread.
You'll also have problems with the threads accessing the UI.
From the code you've posted I'm not sure this really needs to be threaded.

Categories