I am running a BackgroundWorker thread to do a time consuming task. The time consuming task is in another class. I need to pass the progress being made on this separate class running on BackgroundWorker back to the Main Form1 class. I am not sure how to approach this. Please provide suggestions. Thank you in advance.
**// Main Form1 UI Class**
public void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument always contains whatever was sent to the background worker
// in RunWorkerAsync. We can simply cast it to its original type.
DataSet ds = e.Argument as DataSet;
this.createje.ProcessData(this.ds);
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = CreateJE.max;
this.progressBar1.Value = e.Recno;
}
**//Other Class called CreateJE**
public void ProcessData(DataSet ds)
{
//Do time consuming task...
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
**//How do I report progress back to the Main UI?**
//worker.ReportProgress(i * 10);
}
}
}
The cleanest, and most extendable, solution is probably to have your ProcessData() method raise an event, which the BackgroundWorker is listening for. This way ProcessData() doesn't depend on having a BackgroundWorker as a caller. (You would also need to make a way of canceling out of ProcessData()). You can even re-use the ProgressChangedEventArgs if you want. For example (not tested but you get the idea?):
partial class Form1 {
public void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) {
//e.Argument always contains whatever was sent to the background worker
// in RunWorkerAsync. We can simply cast it to its original type.
DataSet ds = (DataSet)e.Argument;
var bgw = (BackgroundWorker)sender;
var eh = new ProgressChangedEventHandler((o,a) => bgw.ReportProgress(a.ProgressPercentage));
createje.ProgressChanged += eh;
this.createje.ProcessData(this.ds));
createje.ProgressChanged -= eh; //necessary to stop listening
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = CreateJE.max;
this.progressBar1.Value = e.ProgressPercentage;
}
}
partial class CreateJE {
public event ProgressChangedEventHandler ProgressChanged;
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
var hand = ProgressChanged;
if(hand != null) hand(this, e);
}
public void ProcessData(DataSet ds)
{
for(int i = 1; i <= 10; i++)
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
var e = new ProgressChangedEventArgs(i * 10, null);
}
}
}
The quick and dirty way is to just pass the BackgroundWorker as a parameter to ProcessData(). This is IMHO rather ugly, though, ties you down to using only BackgroundWorkers, and also forces you to define the BackgroundWorker in one place (the main form class) and the returned values of ReportProgress in another (the CreateJE class).
You could also use a timer and report back progress every X ms, querying the CreateJE object for its progress. This seems in-line with the rest of your code. The hangup with this is it would make your CreateJE class not multi-thread-friendly.
The quickest and simplest option would be to declare a delegatein class CreateJE that will report proggress and then hook this to the ReportProgress method of BackgroundWorker.
class CreateJE
{
public Action<int> ReportProgressDelegate{get;set;}
public void ProcessData(DataSet ds)
{
for(int i = 0; i < 10; i++)
{
Thread.Sleep(500);
ReportProgress(i*10);
}
}
private void ReportProgress(int percent)
{
if(ReportProgressDelegate != null)
ReportProgressDelegate(percent);
}
}
In your form, initialize ReportProgressDelegate property of your instance (I assume this.createje refers to a field of the form so OnLoad seems like a good place to do the initialization):
protected override void OnLoad(EventArgs e)
{
this.creatje.ReportProgressDelegate = worker.ReportProgress;
}
After that, you can use the event handlers you already have (backgroundWorker2_DoWork and backgroundWorker2_DoWork).
PS: You should use the same approach with worker.CancellationPending property.
Related
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();
});
}
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);
}
}
I am creating some files from xml data in the background using
Task.Factory.StartNew(() => xmlconvert(xx, yy));
Now, the question is how to show the progress of this method using a StatusStrip control with some message and the progress or at least just a scrolling animation for the progress. I don't just have any idea how would it work.
Update:
First of all, this method 'xmlconvert(xx, yy)' has four different forms depends on the condition user selects at runtime.
In the main form of my application user can select from different conditions to process on the data. Then finally when user click on the Button 'Create' all these conditions are being checked and a suitable method will be called within that button click event. I need to show the progress of this method which is being invoked at runtime.
private void btnCreateRelease_Click(object sender, EventArgs e)
{
// Checks set of conditions
if(cond 1)
{
xmlconvert_1();
}
else if (cond2)
{
xmlconvert_2();
}
else if (cond3)
{
xmlconvert_3();
}
else if (cond4)
{
xmlconvert_4();
}
}
I want to show progress of one of these methods which will be invoked at runtime depends on the condition.
Thanks a lot.
You can use the BackgroundWorker for this, and it's pretty simple, too. Here's a sample to get you going:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do your work in here.
xmlconvert(xx, yy);
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
}
And here's the link to the documentation.
To get it to work in your scenario, I would suggest you add a Progress bar to your StatusStrip control and update it from within the backgroundWorker1_ProgressChanged event.
If you wish just to show, that your app is not hang may help following approach:
public static class ActionExtensions
{
public static void RunWithMargueProgress(this Action action)
{
var progressForm = new ProgressForm();
progressForm.Show();
Task.Factory.StartNew(action)
.ContinueWith(t =>
{
progressForm.Close();
progressForm.Dispose();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
Where ProgressForm would be a simple form with ProgressBar, that is set to Marquee style. If you have idea, how it is progressing, it is better to show progress for user and use BackgroundWorker.
As long as it's parameter is Action, it is easily reusable.
Usage would be:
private void button_Click(object sender, EventArgs e)
{
Action action = () => Thread.Sleep(5000);
action.RunWithMargueProgress();
}
If you have control in status strip, that you wish to animate, you can do it like this:
public static void RunWithMargueProgress(this Action action, ToolStripProgressBar progressBar)
{
progressBar.Style = ProgressBarStyle.Marquee;
progressBar.MarqueeAnimationSpeed = 30;
Task.Factory.StartNew(action)
.ContinueWith(t =>
{
progressBar.MarqueeAnimationSpeed = 0;
progressBar.Style = ProgressBarStyle.Continuous;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
Usage would be pretty much the same:
private void button_Click(object sender, EventArgs e)
{
Action action = () => Thread.Sleep(5000);
action.RunWithMargueProgress(ToolStripProgressBar);
}
I am using a background worker to update some tables in sqlserver. the progressbar max is getting set to the correct value, the progressbar value is being incremented, the backgroundworker progresschanged is being called correctly with correct value, yet the bar is not progressing.
here is the code for the form
in the background_dowork method there is a loop which calls updateProgressBarValue which works with correct values.
public InterfaceConvertLonLat()
{
InitializeComponent();
Shown += new EventHandler(Form1_Shown);
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
}
public void ConvertLonLat_Load(object sender, EventArgs e)
{
}
public void updateProgressBarValue()
{
progressBar1.Value++;
backgroundWorker1.ReportProgress(progressBar1.Value);
}
public void setProgressBarMax(int max)
{
progressBar1.Maximum = max;
MessageBox.Show("setprogressbarmax " + max);
}
public void Form1_Shown(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
convert.OSGB36ToWGS84("paf");
}
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
here is the loop contained in another class which calls updateprogressbarvalue, this is being fired and as stated backgroundworker1_progressChanged is being fired but the bar is not moving.
con.setProgressBarMax(address.Tables[0].Rows.Count);
foreach (DataRow LonLat in address.Tables[0].Rows)
{
con.updateProgressBarValue();
Double lon = 0;
Double lat = 0;
lat = Convert.ToDouble(LonLat["LTO"]);
lon = Convert.ToDouble(LonLat["LGO"]);
LocalToWGS84(ref lat, ref lon, OGB_M);
cmd1.Parameters["#LTW"].Value = lat;
cmd1.Parameters["#LGW"].Value = lon;
string dbQuery1 = "update " + tableName + " set LTW = #LTW, LGW = #LGW";
cmd1.CommandText = (dbQuery1);
cmd1.CommandType = CommandType.Text;
cmd1.Connection = conn;
cmd1.ExecuteNonQuery();
}
}
catch (Exception e)
{
MessageBox.Show("error converting: " + e.Message);
}
finally
{
conn.Close();
}
When reporting progress you need to fire an event from the background worker to tell the progressbar it needs updating. This can be done using the below:
backgroundWorker1.ReportProgress(10);
Change the value to what you need to demonstrate increased progress in your code. The progress changed event will mostly run on the same thread as your GUI so you should have no cross thread issues. One exception is if your form is being called from Excel via addin in which case Excel will be on the main thread.
You've got a number of issues - Your UpdateprogressBarValue() just increases the value of the progress bar but doesn't keep track of how many times its been called / what the current value is - so if you call it 101 times (assuming a range of 0-100), you'll get an OutOfRangeException
Your DoWork() method doesn't seem to call the update at all (either directly or by raising an event).
You can use events to do this but you're better off using delegates or perhaps anonymous functions. Something like...
public void setProgress(int value) {
progressBar1.invoke(delegate{ progressBar1.Value = value; }
}
then just call setProgress(0) through setProgress(progressBar1.MaxValue) from your DoWork() method
The following is seriously wrong:
public void updateProgressBarValue()
{
progressBar1.Value++; // not thread-safe
backgroundWorker1.ReportProgress(progressBar1.Value);
}
ReportProgress() is intended to be called form DoWork, it should not even read a Control property.
You should maintain a counter in the foreach loop and feed that to the progress mechanism.
Now this does not directly indicate why it doesn't move but you do not have a Completed handler. Are you sure the process finishes at all?
If an exception escapes your DoWork you will never know what happened.
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 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, progress e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
I think this might be caused by the fact that the UI in windows forms is running in its own thread/context. In this case you probably need to use Invoke to make adjustments to the UI.
Something like this:
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Invoke(new ProgressDelegate(UpdateProgress), e.ProgressPercentage);
}
delegate void ProgressDelegate(decimal value);
private void UpdateProgress(decimal value)
{
progressBar1.Value = value;
}
In My application have time consuming process.There fore i try to do that operation in separate thread.Even i Stared it separate thread my Main UI still freezes during the time of long running process.But still i couldn't figure out the reason for that?Some thing wrong in my code?
My Event Hander Code
private void BtnloadClick(object sender, EventArgs e)
{
if (null != cmbSource.SelectedItem)
{
string selectedITem = ((FeedSource) cmbSource.SelectedItem).Url;
if (!string.IsNullOrEmpty(selectedITem))
{
Thread starter = new Thread(() => BindDataUI(selectedITem));
starter.IsBackground = true;
starter.Start();
}
}
private void BindDataUI(string url)
{
if (feedGridView1.InvokeRequired)
{
BeginInvoke(new Action(() => BindDataGrid(url)));
}
else
BindDataGrid(ss);
}
private void BindDataGrid(string selectedItem)
{
for (int i = 0; i < 10; i++)
{
//Time consuming Process
}
}
Your thread is completely useless :-)
In your thread you are executing BindDataUI which marshals the execution back to the UI thread using Invoke.
Your complete code is equivalent to this:
private void BtnloadClick(object sender, EventArgs e)
{
if (null != cmbSource.SelectedItem)
{
string selectedITem = ((FeedSource) cmbSource.SelectedItem).Url;
if (!string.IsNullOrEmpty(selectedITem))
{
BindDataGrid(selectedITem);
}
}
private void BindDataGrid(string selectedItem)
{
for (int i = 0; i < 10; i++)
{
//Time consuming Process
}
}
It would be better to only marshal these parts of BindDataGrid to the UI thread that really need to run on this thread because they need to update the UI.