I have spent the whole day trying to make my application use threads but with no luck. I have read much documentation about it and I still get lots of errors, so I hope you can help me.
I have one big time consuming method which calls the database and updates the GUI. This has to happen all the time(or about every 30 seconds).
public class UpdateController
{
private UserController _userController;
public UpdateController(LoginController loginController, UserController userController)
{
_userController = userController;
loginController.LoginEvent += Update;
}
public void Update()
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
while(true)
{
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerAsync();
}
}
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
_userController.UpdateUsersOnMap();
}
}
With this approach I get an exception because the backgroundworker is not and STA thread(but from what I can understand this is what I should use). I have tried with a STA thread and that gave other errors.
I think the problem is because I try to update the GUI while doing the database call(in the background thread). I should only be doing the database call and then somehow it should switch back to the main thread. After the main thread has executed it should go back to the background thread and so on. But I can't see how to do that.
The application should update the GUI right after the database call. Firering events don't seem to work. The backgroundthread just enters them.
EDIT:
Some really great answers :) This is the new code:
public class UpdateController{
private UserController _userController;
private BackgroundWorker _backgroundWorker;
public UpdateController(LoginController loginController, UserController userController)
{
_userController = userController;
loginController.LoginEvent += Update;
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += backgroundWorker_DoWork;
_backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
}
public void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_userController.UpdateUsersOnMap();
}
public void Update()
{
_backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//UI update
System.Threading.Thread.Sleep(10000);
Update();
}
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Big database task
}
}
But how can I make this run every 10 second? System.Threading.Thread.Sleep(10000) will just make my GUI freeze and while(true) loop in Update() as suggested gives an exception(Thread too busy).
You need to declare and configure the BackgroundWorker once - then Invoke the RunWorkerAsync method within your loop...
public class UpdateController
{
private UserController _userController;
private BackgroundWorker _backgroundWorker;
public UpdateController(LoginController loginController, UserController userController)
{
_userController = userController;
loginController.LoginEvent += Update;
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
_backgroundWorker.WorkerReportsProgress= true;
}
public void Update()
{
_backgroundWorker.RunWorkerAsync();
}
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
// Do the long-duration work here, and optionally
// send the update back to the UI thread...
int p = 0;// set your progress if appropriate
object param = "something"; // use this to pass any additional parameter back to the UI
_backgroundWorker.ReportProgress(p, param);
}
}
// This event handler updates the UI
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Update the UI here
// _userController.UpdateUsersOnMap();
}
}
You have to use the Control.InvokeRequired property to determine if you are on a background thread. Then you need to invoke your logic that modified your UI via the Control.Invoke method to force your UI operations to occur on the main thread. You do this by creating a delegate and passing it to the Control.Invoke method. The catch here is you need some object derived from Control to call these methods.
Edit: As another user posted, if yo you can wait to the BackgroundWorker.Completed event to update your UI then you can subscribe to that event and call your UI code directly. BackgroundWorker_Completed is called on the main app thread. my code assumes you want to do updates during the operation. One alternative to my method is to subscribe to the BwackgroundWorker.ProgressChanged event, but I believe you'll need to still call Invoke to update your UI in that case.
for example
public class UpdateController
{
private UserController _userController;
BackgroundWorker backgroundWorker = new BackgroundWorker();
public UpdateController(LoginController loginController, UserController userController)
{
_userController = userController;
loginController.LoginEvent += Update;
}
public void Update()
{
// The while loop was unecessary here
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerAsync();
}
public delegate void DoUIWorkHandler();
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// You must check here if your are executing on a background thread.
// UI operations are only allowed on the main application thread
if (someControlOnMyForm.InvokeRequired)
{
// This is how you force your logic to be called on the main
// application thread
someControlOnMyForm.Invoke(new
DoUIWorkHandler(_userController.UpdateUsersOnMap);
}
else
{
_userController.UpdateUsersOnMap()
}
}
}
You should remove the while(true), you are adding infinite event handlers and invoking them infinite times.
You can use the RunWorkerCompleted event on the backgroundWorker class to define what should be done when the background task has completed. So you should do the database call in the DoWork handler, and then update the interface in the RunWorkerCompleted handler, something like this:
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += (o, e) => { longRunningTask(); }
bgw.RunWorkerCompleted += (o, e) => {
if(e.Error == null && !e.Cancelled)
{
_userController.UpdateUsersOnMap();
}
}
bgw.RunWorkerAsync();
In addition to previous comments, take a look at www.albahari.com/threading - best doc on threading you will ever find. It will teach you how to use the BackgroundWorker properly.
You should update the GUI when the BackgroundWorker fires Completed event (which is invoked on UI thread to make it easy for you, so that you don't have to do Control.Invoke yourself).
Here's a source code pattern you can use based on some WinForms example code, but you can apply it for WPF as well very easily. In this example, I am redirecting output to a Console which I then use to let the background worker write some messages to a textbox while it is processing.
It consists of:
A helper class TextBoxStreamWriter used to redirect console output to a textbox
A background worker writing to the redirected console
A progress bar which needs to be reset after completion of background worker
Some text boxes (txtPath and txtResult), and a "Start" button
In other words, there is some background task which needs to interact with the UI. Now I am going to show how that is done.
From the context of the background task, you need to use Invoke to access any UI element. I believe the simplest way to do that is to use lambda expression syntax, like
progressBar1.Invoke((Action) (() =>
{ // inside this context, you can safely access the control
progressBar1.Style = ProgressBarStyle.Continuous;
}));
To update the ProgressBar, a local method like
private void UpdateProgress(int value)
{
progressBar1.Invoke((Action)(() => { progressBar1.Value = value; }));
}
helps. It is passing the value parameter to the progress bar as a closure.
This is the helper class TextBoxStreamWriter, which is used to redirect console output:
public class TextBoxStreamWriter : TextWriter
{
TextBox _output = null;
public TextBoxStreamWriter(TextBox output)
{
_output = output;
}
public override void WriteLine(string value)
{
// When character data is written, append it to the text box.
// using Invoke so it works in a different thread as well
_output.Invoke((Action)(() => _output.AppendText(value+"\r\n")));
}
}
You need to use it in the form load event as follows (where txtResult is a textbox, to which the output will be redirected):
private void Form1_Load(object sender, EventArgs e)
{
// Instantiate the writer and redirect the console out
var _writer = new TextBoxStreamWriter(txtResult);
Console.SetOut(_writer);
}
There is also a button on the form which starts the background worker, it passes a path to it:
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(txtPath.Text);
}
This is the workload of the background worker, note how it uses the console to output messages to the textbox (because of the redirection that was set up earlier):
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var selectedPath = e.Argument as string;
Console.Out.WriteLine("Processing Path:"+selectedPath);
// ...
}
The variable selectedPath consists of the path that was passed to the backgroundWorker1 earlier via the parameter txtPath.Text, it is being accessed via e.Argument.
If you need to reset some controls afterwards, do it in the following way (as already mentioned above):
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Invoke((Action) (() =>
{
progressBar1.MarqueeAnimationSpeed = 0;
progressBar1.Style = ProgressBarStyle.Continuous;
}));
}
In this example, after completion, a progress bar is being reset.
Important: Whenever you access a GUI control, use Invoke as I did in the examples above.
Using Lambda's makes it easy, as you could see in the code.
And here's the complete example, which runs in LinqPad 6 (just copy and paste it into an empty C# Program query) - I decided to use LinqPad this time so you can learn something new, because you all know how to create a new Windows Forms project in Visual Studio (and if you still want to do so, just copy the events below and drag and drop the controls to the form):
// see: https://stackoverflow.com/a/27566468/1016343
using System.ComponentModel;
using System.Windows.Forms;
BackgroundWorker backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
ProgressBar progressBar1 = new ProgressBar() { Text = "Progress", Width = 250, Height=20, Top=10, Left=0 };
TextBox txtPath = new TextBox() { Text =#"C:\temp\", Width = 100, Height=20, Top=30, Left=0 };
TextBox txtResult = new TextBox() { Text = "", Width = 200, Height=250, Top=70, Left=0, Multiline=true, Enabled=false };
Button btnStart = new Button() { Text = "Start", Width = 100, Height=30, Top=320, Left=0 };
void Main()
{
// see: https://www.linqpad.net/CustomVisualizers.aspx
// Instantiate the writer and redirect the console out
var _writer = new TextBoxStreamWriter(txtResult);
Console.SetOut(_writer);
// wire up events
btnStart.Click += (object sender, EventArgs e) => btnStart_Click(sender, e);
backgroundWorker1.DoWork += (object sender, DoWorkEventArgs e) => backgroundWorker1_DoWork(sender, e);
backgroundWorker1.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e)
=> backgroundWorker1_RunWorkerCompleted(sender, e);
using var frm = new Form() {Text="Form", Width = 300, Height=400, Top=0, Left=0};
frm.Controls.Add(progressBar1);
frm.Controls.Add(txtPath);
frm.Controls.Add(txtResult);
frm.Controls.Add(btnStart);
// display controls
frm.ShowDialog();
}
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(txtPath.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
InitProgress();
var selectedPath = e.Argument as string;
Console.Out.WriteLine("Processing Path: " + selectedPath);
UpdateProgress(0); Thread.Sleep(300); UpdateProgress(30); Thread.Sleep(300);
UpdateProgress(50); Thread.Sleep(300);
Console.Out.WriteLine("Done.");
// ...
}
private void UpdateProgress(int value)
{
progressBar1.Invoke((Action)(() =>
{
progressBar1.Value = value;
}));
}
private void InitProgress()
{
progressBar1.Invoke((Action)(() =>
{
progressBar1.MarqueeAnimationSpeed = 0;
progressBar1.Style = ProgressBarStyle.Continuous;
}));
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
UpdateProgress(100); // always show 100% when done
}
// You can define other methods, fields, classes and namespaces here
public class TextBoxStreamWriter : TextWriter
{
TextBox _output = null;
public TextBoxStreamWriter(TextBox output)
{
_output = output;
}
public override Encoding Encoding => throw new NotImplementedException();
public override void WriteLine(string value)
{
// When character data is written, append it to the text box.
// using Invoke so it works in a different thread as well
_output.Invoke((Action)(() => _output.AppendText(value + "\r\n")));
}
}
The if-statement in #Lee's answer should look like:
bgw.RunWorkerCompleted += (o, e) => {
if(e.Error == null && !e.Cancelled)
{
_userController.UpdateUsersOnMap();
}
}
...if you want to invoke UpdateUsersOnMap(); when there are no errors and BgWorker hasn't been cancelled.
Related
i come from a java environment and just recently started to learn C#.
(Please scroll a t the end of the question to see solution)
I'm Trying to use a background Worker to fetch some data from a Webservice do some calculations and update the UI, but i cant seem to make it report the progress back
So i Have my Form1.cc which contains the MainForm class that represents my UI Form (contains 2 date pickers , 1 progress bar and a button).
on the button i have binded the following click handler:
private void runReport_Click(object sender, EventArgs e)
private void runReport_Click(object sender, EventArgs e)
{
//MessageBox.Show("button pressed\n datefrom "+dateFrom.Value.ToString("yyyy-MM-dd" ));
AdStage data=new AdStage(dateFrom.Value.ToString("yyyy-MM-dd"), dateTo.Value.ToString("yyyy-MM-dd"));
//this.progressLabel.Text = "Fetching Data From Adstage";
//data.setUIProgressItems(progressLabel, this.progressBar);
data.setUI(this);
data.startWorker();
}
On the Adstage.cs i have all my logic to handle staff on the background.
/*constructor*/
public AdStage(String dateFrom, String dateTo)
{
//set the dates
setDates(dateFrom, dateTo);
}
public void startWorker()
{
doBg();//start bg worker...
}
public void setUI(MainForm ui)
{
this.ui = ui;
}
private void setDates(String dateFrom, String dateTo)
{
if (dateFrom.Equals(dateTo))
{
this.dateTo = this.dateTo = dateFrom;
}
else
{
this.dateFrom = dateFrom;
this.dateTo = dateTo;
}
}
private void doRequest(String offset,String url= null,BackgroundWorker worker=null,int p=0)
{
//all of the logic that gets data from the web serivces is here
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(String.Format("worker_runWorkerCompleted"));
//update ui once the job has finished..
MessageBox.Show("Data Fetched! Total Campaigns: "+this.campaigns.Count());
//this.ui.updateProgress("Fetched " + this.campaigns.Count() + " campaigns",100);
//this.ui.progressLabel.Text = "Fetched "+this.campaigns.Count()+" campaigns";
}
public void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Testing worker_ProgressChanged: "+e.ProgressPercentage.ToString());
MessageBox.Show("Progress: " + this.campaigns.Count());
this.ui.progressLabel.Text = e.ProgressPercentage.ToString();
}
And this is my DoWork function
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine(String.Format("worker_doWork"));
//do all major background work here..
BackgroundWorker worker = sender as BackgroundWorker;
worker.ReportProgress(1);
doRequest(offset,null,worker);
(worker as BackgroundWorker).ReportProgress(99, null);
//worker.ReportProgress(100);
}
So even id if use the report progress inside of the doRequest() function its like the worker_ProgressChanged is never called. The worker goes on, fetches all pages from the web service, and only reports back when finished.
The worker_ProgressChanged event never occurs..
EDIT: clarifying my code to help people understand what i am doing :)
I have the worker be created in a method called doBG();
private void doBg()
{
Console.WriteLine(String.Format("BG WORKER STARTED"));
this.worker.DoWork += worker_DoWork;
this.worker.RunWorkerCompleted += worker_RunWorkerCompleted;
this.worker.WorkerReportsProgress = true;
worker.RunWorkerAsync();
}
When the buttn runReport is clicked, i have an instance of the class Adstage be created. ( AdStage data=new AdStage(dateFrom.Value.ToString("yyyy-MM-dd"), dateTo.Value.ToString("yyyy-MM-dd"));)
Then on that instance i set the ui (this is just so i can access the mainForm members from the Adstage class)
and then i start the background worker from the mainFOrm by making a call to data.startWorker(); (which basically just call the doBG() functions of the Adstage class). This is because i have set the doBG() to be private on the Adstage class.
EDIT 2:
Adding this.worker.ProgressChanged += worker_ProgressChanged; inside of the doBg() function, seems to do the trick , thank you Dirk for pointing that out and thank you Machine Learning for the good tips :)
Also to anyone having same issues, you can also update the ui using delegates.
Check this answer here to get an idea how to do it: https://stackoverflow.com/a/3303276/514657 (it really helped me understand how to work with delegates)
Don't pass the UI form to the Background worker, but write the ProgressChanged in the UI form.
So, again, ProgressChanged (as well as RunWorkerCompleted) must not be a method of the worker because you can't update the UI from another thread.
What I'm trying to achieve is simple. I have a dynamic timer (one that can be changed by the user) which calls on background worker to go and fetch the user's external IP address. The combination of Timer and BackgroundWorker is causing some problems. Here's the code:
namespace IPdevices
{
/// <summary>
/// Interaction logic for Main.xaml
/// </summary>
public partial class Main : Window
{
private readonly BackgroundWorker worker;
private IPret iprep;
private Timer timer;
public Main(Client client)
{
InitializeComponent();
iprep = new IPret();
startClock();
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerReportsProgress = true;
worker.ProgressChanged += worker_ProgressChanged;
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ipAdd.Content = e.UserState;
}
private void startClock()
{
timer = new Timer();
timer.Interval = 2000;
timer.Elapsed += new ElapsedEventHandler(clockTimer_Tick);
timer.Start();
}
private void clockTimer_Tick(object sender, ElapsedEventArgs e)
{
timer.Stop();
worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Checking ip");
iprep.refresh();
worker.ReportProgress(0, iprep.getExternalIp());
Console.WriteLine("Found ip");
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
timer.Start();
}
}
}
Essentially, once the timer fires, I wish to fetch the ip address and output on a label in the application. However, I get an exception in the ProgressChanged method saying that it can't be changed because another thread owns it. Which thread is that? Is it the iprep that is owned by another thread? In fact, RunWorkerCompleted never gets fired. I'm having trouble understanding which threads own what and how objects are locked...Any insight would be appreciated.
This appears to fix it in my test of it
private void clockTimer_Tick(object sender, ElapsedEventArgs e)
{
timer.Stop();
Action a = () =>
{
worker.RunWorkerAsync();
};
Application.Current.Dispatcher.BeginInvoke(a);
}
Also, I'll note this is consistent behavior for Timer in WPF (I hadn't used it in WPF before); trying ipAdd.Content = "Tick"; in the clockTimer_Tick causes the same error. System.Timers.Timer's tick event does not happen on the UI thread.
Replace all your code by the few lines shown below. The Tick handler is executed in the UI thread. Still it asynchronously runs a background operation and does not block the UI thread.
private void StartClock()
{
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += async (o, e) => await GetIP();
timer.Start();
}
private async Task GetIP()
{
Debug.WriteLine("Checking ip");
await Task.Run(() =>
{
// Get the IP asynchronously here
});
Debug.WriteLine("Found ip");
// Update the UI here
}
ipAdd is an UI element if I am not mistaken. If it is then the problem lies on cross threading.
What happened is that Background worker is going to be running on a different thread than the UI thread. If you want to modify UI element's property you need to do it on the UI thread. One option is to use Dispatcher.Invoke but since you are using WPF, there is a better way to do it.
Do a search about MVVM design patter and move the background code into View Model. Then you could do something like
string _XXContent
public string XXContent
{
get
{
return _XXContent;
}
set
{
_XXContent = value;
OnPropertyChanged("XXContent");
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
XXContent = e.UserState;
}
xaml :
<TextBox Content={Binding XXContent}/>
Edit:
If you are on c# 5 then you should look into async/IProgress as well an get rid of Background worker.
I have create a backgroundworker in an class it works, but if i call and wait until the end run, call it for the second time it will do the same process twice
i thinks there is somthing wrong with bw.DoWork +=
private void button1_Click(object sender, EventArgs e)
{
nptest.test.start("null", "null");
}
namespace nptest
{
class test
{
public static void start(string str, string strb)
{
if (bw.IsBusy != true)
{
bw.WorkerSupportsCancellation = true;
bw.DoWork += (obj, e) => bw_DoWork(str, strb);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
}
private static BackgroundWorker bw = new BackgroundWorker();
private static void bw_DoWork(string str, string strb)
{
System.Windows.Forms.MessageBox.Show("initializing BackgroundWorker");
}
private static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
Console.WriteLine("Canceled");
}
else if (!(e.Error == null))
{
Console.WriteLine("Error: " + e.Error.Message);
}
bw.Dispose();
}
}
}
problem solved
class test
{
private static List<object> arguments = new List<object>();
// initializing with program startup
public static void bwinitializing()
{
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
public static void start(string str, string strb)
{
if (bw.IsBusy != true)
{
arguments.Clear();
arguments.Add(str);
arguments.Add(strb);
bw.RunWorkerAsync(arguments);
}
}
private static BackgroundWorker bw = new BackgroundWorker();
private static void bw_DoWork(object sender, DoWorkEventArgs e)
{
List<object> genericlist = e.Argument as List<object>;
System.Windows.Forms.MessageBox.Show("BackgroundWorker " + genericlist[0]);
}
I would suspect that multiple DoWork events are being inadvertently added.
That is, every time the start method is called it registers a new DoWork event handler. This adds and does not replace the existing handler DoWork handler. So then there will be multiple DoWork handlers called subsequent times .. 1, 2, 3, etc.
// creates a NEW delegate and adds a NEW handler
bw.DoWork += (obj, e) => bw_DoWork(str, strb);
I would recommend not using a closure here, but rather just use a Method Group (with implicit conversion to a delegate) and then pass the data to the RunWorkerAsync call (there is a form that takes an argument for data).
The RunWorkerCompleted += line doesn't have this issue because it is passed a delegate from a Method Group (which is guaranteed to always evaluate to the same delegate object1). Thus the repeated += calls for that line will replace the handler.
Example:
class MyData {
public string StrA { get; set; }
}
// These only need to be setup once (and should be for clarity).
// However it will be "ok" now if they are called multiple times
// as, since the delegates are the same, the += will
// act as a replacement (as it replaces the previous delegate with itself).
bw.WorkerSupportsCancellation = true;
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
// Pass data via argument
bw.RunWorkerAsync(new MyData {
StrA = str,
});
void bw_DoWork (object sender, DoWorkEventArgs e) {
var data = (MyData)e.Argument;
var str = data.StrA;
// stuff
}
1 I am not sure if it is guaranteed to be reference-equals equality, but using this approach allows for stable invoking of += and -= from the delegate from the Method Group even if obtained by new DelegateType(MethodGroup).
Wrt. my comment in the main post: if UI elements are accessed from a thread on which they were not created then there will fun "Cross-thread operation exceptions". I believe this usage of a Message Box is "okay" (when not created with an owner from another thread), but the practice of accessing the UI in a BackgroundWorker's DoWork is generally dubious.
Also, do not call bw.Dispose() here; dispose it with the owning container or context. It appears to be nice and benign in this case, but only do it when that BGW instance will never be used again. Calling it from an event handler is also dubious as the BGW is still "active".
I have encounter same problem as above commenter "Power-Mosfet"
and in the end, added a new BackgroundWorker() then assigned to the global bw value will fix my problem.
code is, change from:
private BackgroundWorker gBgwDownload;
private void yourFunction_bw(xxx)
{
// Create a background thread
gBgwDownload.DoWork += bgwDownload_DoWork;
gBgwDownload.RunWorkerCompleted += bgwDownload_RunWorkerCompleted;
//omited some code
gBgwDownload.RunWorkerAsync(paraObj);
}
to:
private BackgroundWorker gBgwDownload;
private void yourFunction_bw(xxx)
{
// Create a background thread
gBgwDownload = new BackgroundWorker(); /* added this line will fix problem */
gBgwDownload.DoWork += bgwDownload_DoWork;
gBgwDownload.RunWorkerCompleted += bgwDownload_RunWorkerCompleted;
//omited some code
gBgwDownload.RunWorkerAsync(paraObj);
}
There is also another reason. look for DoWorkEventHandler in its generated code InitializeComponent() If you have generated it through compnent UI properties and also registering it yourself.
Because if you register it again it will not override the previous one but will add another event and will call twice.
In my case, BackgroundWorker was running twice because in the constructor class of my form I declared the DoWork, ProgressChanged and RunWorkerCompleted event handlers, but it was already declared by Visual Studio 2013 in Designer part of this form class.
So, I just deleted my declarations and it worked fine.
thank you....this code is working fine... creating new intance for backroundworker is good idea....
Now we can call this function in for/while loop and can run multiple backgroundworker process.
I coded like this
when button click is done.. without distrubting the main thread flow... multiple process will be running back side....
i just used messagebox to pop up..but we can do timetaking process to run in "bgwDownload_DoWork" function... and multiple process will be created... and her we need not check the BackgroundWorker is busy or not...
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
yourFunction_bw(i);
}
private BackgroundWorker gBgwDownload;
private void yourFunction_bw(int i)
{
// Create a background thread
gBgwDownload = new BackgroundWorker(); // added this line will fix problem
gBgwDownload.DoWork += bgwDownload_DoWork;
gBgwDownload.RunWorkerAsync(i);
}
private void bgwDownload_DoWork(object sender, DoWorkEventArgs e)
{
int stre = (int)e.Argument;
MessageBox.Show(stre.ToString ()); // time taken process can be added here
}
I ran into this problem today, I put a background worker on a popup form that was doing a long running task when I noticed that every time I showed the form the background worker RunWorkerCompleted event was being called multiple times.
My problem was that I was not disposing of the form after closing it, which meant every time I showed the form it added another handler to the even each time.
Disposing of the form when finished with it solved my problem. Just wanted to mention it here as I came across this page when I went looking for a solution for my situation.
I removed the control from the designer and instantiate a new WorkerProcess in Code:
example:
var bwProcess = new BackgroundWorker();
bwProcess.DoWork += new DoWorkEventHandler(bwProcess_DoWork);
bwProcess.RunWorkerCompleted += bwProcess_RunWorkerCompleted;
What should be straight forward is not here and I couldnt find a way yet in spite of reading a lot.
I have a button which executes a time consuming function. So on clicking the button should show time elapsed in milliseconds in a label with an interval of 500 ms. And when the desired result is achieved I want the timer to stop. I dont just need the final time (the total time consumed) in a label, but the label should dynamically show the time being elapsed. My code would be:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1();
c.StartClock(ref label12);
Utility.PopulateHistory(dgvRecords_history, _util); //time consuming function
c.StopClock();
}
And in Class1 I write this:
internal void StartClock(ref Label l)
{
Timer t = new Timer();
t.Interval = 500;
t.Enabled = true;
t.Tag = l;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
int i;
bool stop;
void t_Tick(object sender, EventArgs e)
{
if (stop)
{
((Timer)sender).Stop();
return;
}
((Label)((Timer)sender).Tag).Text = (++i).ToString();
}
internal void StopClock()
{
i = 0;
stop = true;
}
What happens is, the t_Tick event is fired only after the complete code under button event is fired. That is the tick event is fired after it goes through the StopClock function! I got no idea why on earth it should be that!
2 questions basically:
How can my requirement be achieved in the right way to handle these? I know I should use other built in classes to evaluate performance, but this is just for display purpose. For this, what is the ideal approach?
Why is my code not working?
EDIT: I have used here System.Windows.Forms Timer here, but the result is not any different with System.Timers Timer
The problem is that your long-running task is also running on the UI thread. So the timer can't fire and update the UI, since the thread is busy handling the long-running task.
Instead, you should use a BackgroundWorker to handle the long-running task.
In code:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1(ref label12);
c.StartClock();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, e) =>
{
// time consuming function
Utility.PopulateHistory(dgvRecords_history, _util);
};
backgroundWorker.RunWorkerCompleted += (s, e) =>
{
c.StopClock();
};
backgroundWorker.RunWorkerAsync();
}
As ChrisWue noted, since you now have the long-running task in a separate thread, it needs to invoke any access to the UI controls on the UI thread.
If your long-running task just needs some data from the UI to start, you can pass that data as parameter of RunWorkerAsync(). If you need to output some result data to the UI, you can do that in the handler of the RunWorkerCompleted event. If you occasionally need to update the UI as progress is being made, you can do that in the handler of the ProgressChanged event, calling ReportProgress() in your DoWork handler.
If none of the above are needed, you could use the ThreadPool, as in StaWho's answer.
Your time consuming function is blocking the main thread. You can use BackgroundWorker or below trick:
public Form1()
{
InitializeComponent();
t.Tick +=new EventHandler(t_Tick);
t.Interval = 500;
}
int timeElapsed = 0;
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
private void button1_Click(object sender, EventArgs e)
{
t.Start();
ThreadPool.QueueUserWorkItem((x) =>
{
TimeConsumingFunction();
});
}
void TimeConsumingFunction()
{
Thread.Sleep(10000);
t.Stop();
}
void t_Tick(object sender, EventArgs e)
{
timeElapsed += t.Interval;
label1.Text = timeElapsed.ToString();
}
Add the timer to the Components collection of the form. Or store the timer in a field in the class.
The timer is garbage collected because it is not longer reachable when your method returns.
I don't know about your long running code, but out should new run on a separate thread, or make calls to Application.DoEvents
(And remove the ref in your code, it is not used).
#Dainel Rose's answer worked for me perfectly, but only if invalid cross thread operation is handled. I could do so like:
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1(ref label12);
c.StartClock();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += ((s, e) =>
{
// time consuming function
Utility.PopulateHistory(dgvRecords_history, _util);
});
backgroundWorker.RunWorkerCompleted += ((s, e) =>
{
c.StopClock();
});
backgroundWorker.RunWorkerAsync();
}
And in the Utility class where the time consuming function runs,
internal static void PopulateHistory(DataGridView dgv, Utility util)
{
SetDataGridView_History(dgv, util);
}
delegate void UpdateDataGridView_History(DataGridView dgv, Utility util);
static void SetDataGridView_History(DataGridView dgv, Utility util)
{
if (dgv.InvokeRequired)
{
UpdateDataGridView_History updaterDelegate = new UpdateDataGridView_History(SetDataGridView_History);
((Form)util._w).Invoke(updaterDelegate, new object[] { dgv, util });
}
else
//code that utilizes UI thread (long running process in my case)
}
Thanks all who helped. I'm marking Daniel's answer..
I have a WPF application that executes external programs to process media files, and so that the GUI doesn't freeze when the media files are being processed, I execute the process on a separate thread through backgroundworker.
private void BackgroundWorkerExecProcess(Process process)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = false;
worker.DoWork += DoWork;
worker.RunWorkerCompleted += WorkerCompleted;
worker.RunWorkerAsync(process);
}
void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
Process process = e.Argument as Process;
process.Start();
string stderr = process.StandardError.ReadToEnd();
//I want to display stderr on main thread
process.WaitForExit();
}
void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//some code to update gui telling user that process has finished
}
so, if there is something printed to stderr, I can see it in the debugger, but if I try to do anything with the string stderr, such as if I have a textbox called "_tbLog" and did
_tbLog.Text+=stderr;
I get an error from the compiler about them being on separate threads. is there a way to pass the object from the worker thread to the main thread?
In DoWork, set e.Result to your object. In the WorkerCompleted you can get that object back out... it will once again be e.Result of type object. Just cast it to the object it was. The WorkerCompleted should be on the correct thread.
Here is one of mine:
private void workerUpdateBuildHistory_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
UpdateStatusModel model = (UpdateStatusModel)e.Argument;
BuildService buildService = new BuildService(model.TFSUrl);
e.Result = buildService.UpdateBuildHistoryList(model);
}
private void workerUpdateBuildHistory_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
BuildHistoryListModel model = (BuildHistoryListModel)e.Result;
if (model != null)
{
listViewPastBuilds.Items.Clear();
foreach (var item in model.Builds)
{
listViewPastBuilds.Items.Add(item);
}
}
}
Use your WorkerCompleted event handler to make changes the UI, it runs on the right thread. All you have to do is pass the string to the event handler. Which is what DoWorkEventArgs.Result was designed to do. You'll retrieve it in the event handler from e.Result. Thus:
void DoWork(object sender, DoWorkEventArgs e)
{
//...
e.Result = stderr;
}
void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null) DisplayError(e.Error);
else _tbLog.Text += (string)e.Result;
}
First you need to place whatever result object (in this example, a list of strings) in the DoWorkEventArgs.Result property, then retrieve this object via the RunWorkerCompletedArgs.Result property
Then, hook up an event handler RunWorkedCompleted event of the Background worker and have it pass back whatever object you want in the RunWorkerCompletedEventArgs.Result property.
Example:
void DoWork(object sender, DoWorkEventArgs arg)
{
List<string> results = new List<string>();
results.Add("one");
results.Add("two");
results.Add("three");
arg.Results = results;
}
void WorkComplete(object sender, runWorkerCompelteEventArgs arg)
{
//Get our result back as a list of strings
List<string> results = (List<string>)arg.Result;
PrintResults(results);
}
Note: I have not tested this code, but I believe it should compile.
http://msdn.microsoft.com/en-us/library/system.componentmodel.runworkercompletedeventargs.result.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.aspx
you can also use the dispatcher as #Zembi mentiones:
this.Dispatcher.Invoke( new Action( () => {
_tbLog.Text+=stderr;
} ) );
you can also use TPL to make sure things get run on the right thread
-edit-
Here is a good article on diffrent ways to do ui updates, including using TPL