I have a C# WinForms application with a tab control and several tabs. One of the tabs contains a data grid control - it only has about 10 elements in it but the data is populated by querying multiple servers and thus is slow to load.
When I run my application and select the tab with the datagrid control, the application appears to hang, while its trying to query all the servers and populate the grid.
Instead of hanging I'd like the application to be responsive and for it to display a "please wait..." message which will disappear after the datagrid is populated.
What I've tried to do is create a background worker as such:
if (tabctrl.SelectedTab == tabctrl.TabPages["tabServices"])
{
this.dgrdServices.RowPrePaint += new DataGridViewRowPrePaintEventHandler(dgrdServices_RowPrePaint);
this.dgrdServices.CellContentClick += new DataGridViewCellEventHandler(dgrdServices_CellClick);
BackgroundWorker bw = new BackgroundWorker();
lblLoading.Visible = true;
bw.RunWorkerAsync();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
PopulateServicesDataGrid();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblLoading.Visible = false;
}
private void PopulateServicesDataGrid()
{
int x = 0;
foreach (Service Service in Globals.Services)
{
// Add a row to the datagrid for each service
this.dgrdServices.Rows.Add();
// Update the current service status
Service.Status = Service.Query(Service.Server, Service.Name);
if (Service.Status == "running")
{
this.dgrdServices.Rows[x].Cells[0].Value = Properties.Resources.green_dot;
this.dgrdServices.Rows[x].Cells[4].Value = Properties.Resources.stop_enabled;
}
else
{
this.dgrdServices.Rows[x].Cells[0].Value = Properties.Resources.grey_dot;
this.dgrdServices.Rows[x].Cells[4].Value = Properties.Resources.start_enabled;
}
this.dgrdServices.Rows[x].Cells[1].Value = Service.Server.ToUpper();
this.dgrdServices.Rows[x].Cells[2].Value = Service.FreindlyName;
this.dgrdServices.Rows[x].Cells[3].Value = Service.Status;
this.dgrdServices.Rows[x].Cells[5].Value = "Uninstall";
this.dgrdServices.Rows[x].Cells[6].Value = Service.Name;
x++;
}
}
PopulateServicesDataGrid() contains code which iterates through some objects and queries several different servers for service status.
When I try and run the above though the grid doesn't get populated. If I don't use a background worker and just call PopulateServicesDataGrid directly it does work (albeit the app hangs).
Why isn't the background worker/datagrid populate working?
In your PopulateServicesDataGrid I imagine you're interacting with a UI control, which doesn't work out because the background worker is operating on a different thread than your UI context. You'll need to work out a mechanism to do the work in a way that returns the information you want to put in the grid and then back in your UI thread context (RunWorkerCompleted), populate the grid with the information you come up with in DoWork.
Anytime you're using a background worker, you'll need to split out your interactions with the UI controls, and after the backgroundworker completes resume interaction with your UI.
You're also hooking up the events after calling RunWorkerAsync, hook up your events first then call RunWorkerAsync.
Edit to reflect comment with an example:
Rough example of how you could do this, based on the code I see.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
QueryServices()
}
private void QueryServices()
{
foreach (Service Service in Globals.Services)
{
Service.Status = Service.Query(Service.Server, Service.Name);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
PopulateServicesDataGrid();
lblLoading.Visible = false;
}
private void PopulateServicesDataGrid()
{
//Do everything else you are doing originally in this method minus the Service.Query calls.
}
Method bw_DoWork running in another thread from ThreadPool. Accessing WinForms object from other threads requires synchronization. The best way to do this - use AsyncOperationManager. You should create AsyncOperation in GUI thread and use it inside PopulateServicesDataGrid to send or post results.
Another way - update DataGrid by prepared data inside bw_RunWorkerComplete - it's already synchronized by BackgroundWorker component.
More modern way to do the same - use async tasks, but it requires base level of TPL knowledge.
As in title, I have some bgw I want to call on every button press.
Is this code correct ?
private static BackgroundWorker bgw = null;
private void bttn_Click(...)
{
if(!bgw.IsBusy)
doSomeWorkInBg();
else
MessageBox.Show("Slow down a bit");
}
private void doSomeWorkInBg()
{
if (bgw == null)
{
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
}
bgw.RunWorkerAsync();
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
// do some work that takes time
}
Or maybe I should add RunWorkerCompleted event with "bgw = null;" code or something like that?
You should avoid making your bgw static, because you are using it in non-static context.
When I need to re-run the worker frequently based on the UI event, this is the construct that I usually use:
bool ShouldRunWorkedASAP;
private void bttn_Click(...){
ShouldRunWorkedASAP=true;
if (!bgw.IsBusy) bgw.RunWorkerAsync();
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
while (ShouldRunWorkedASAP) {
ShouldRunWorkedASAP=false;
// do some work that takes time
}
}
This assumes that the worked is instantiated in the class constructor. Basically this code sets the flag that the worker should run ASAP whenever the UI event occurred, then tries to run the worker. If it is already running - then the while() loop inside the worker implementation will schedule the job for the next run as soon as it completes.
This code does not ensure that the worker will run exactly the number of times the user presses the button, not sure if in your case this is required or not.
In my application I have a queue download list which consists of progress bars and the file names. When the user clicks a button the file name and progress bar is instantiated and added to the queue. Files download one at a time and asynchronously. What I want to do is keep all the progress bars of the files that are waiting to be downloaded yellow in color and then turn green when it is being downloaded and then turn blue when they are completed. It currently works if I have CheckForIllegalCrossThreadCalls = false; in the constructor of the custom progress bar. I want to see if there is a way to make thread safe changes to the progress bars.
I have each queue item set up as an object. The queue item objects are created from the main form code (Form1.cs) when a button is pressed and the progress bars are created in the queue item constructor, which is probably where my problem begins. The downloads are started through a function in the queue item object.
Queue Item Snippet
public class QueueItem
{
public bool inProgress;
public QueueBar bar;
public QueueItem(args)
{
bar = new QueueBar();
inProgress = false;
// handle arguments
}
public void Download()
{
// process info
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileAsync(url, #savePath);
}
private long lastByte = 0;
private long newByte = 0;
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
percentValue = e.ProgressPercentage;
bar.Value = e.ProgressPercentage;
newByte = e.BytesReceived;
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
// change bar color
bar.Value = 100;
}
}
Queue Bar Snippet
public class QueueBar : ProgressBar
{
// variables
public QueueBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
// initialize variables
}
// function to change text properties
// function to change color
protected override void OnPaint(PaintEventArgs e)
{
// painting
}
}
Main Function Snippet
public partial class Form1 : Form
{
private List<QueueItem> qItems;
private BackgroundWorker queue;
private void button_Click(object sender, EventArgs e)
{
// basic gist of it
qItems.Add(new QueueItem(args));
Label tmpLabel = new Label();
tmpLabel.Text = filename;
tmpLabel.Dock = DockStyle.Bottm;
splitContainerQueue.Panel2.Controls.Add(tmpLabel);
splitContainerQueue.Panel2.Controls.Add(qItems[qItems.Count - 1].bar);
if (!queue.IsBusy) { queue.RunWorkerAsync(); }
}
private void queue_DoWork(object sender, DoWorkEventArgs e)
{
while (qItems.Count > 0)
{
if (!qItems[0].inProgress && qItems[0].percentValue == 0)
{
qItems[0].inProgress = true;
qItems[0].Download();
}
// else if statements
}
}
I also just tried creating a background worker to create the Queue Items and add the controls asynchronously but that doesn't work since the split container was created on a different thread.
You cannot call a UI control (created on your UI thread) from another thread safely - you need to use InvokeRequired / BeginInvoke() for such calls. When calling BeginInvoke() you'll pass a delegate; something like this (just some sample code, yours will look slightly different):
private void SomeEventHandler ( object oSender, EventArgs oE )
{
if ( InvokeRequired )
{
MethodInvoker oDelegate = (MethodInvoker) delegate
{
SomeEventHandler ( oSender, oE );
};
BeginInvoke ( oDelegate );
return;
}
else
{
// already on the correct thread; access UI controls here
}
}
You also cannot create your progress bars away from the UI thread - you need to create all your controls as part of your UI and then if you need to access these progress bars from your queue items, you'll have to pass in a reference to the progress bar. When you try to access the progress bar, you'll do
if ( bar.InvokeRequired ) { ... }
to determine if you're trying to call it from the right thread.
The reason for this mess is because controls handle many of their property updates through messages and those messages must be delivered synchronously, in the correct order. The only way to ensure this (without some very complex coding) is to create all controls on the same thread where the thread runs a message pump.
When I click my ActionButton, there is a timer that starts and after 3 seconds, it must fire a methode to change the current ContentPage to the another page.
But i get a message : The calling thread cannot access this object because a different thread owns it. I dont understand what i am doing wrong. But if i put the ChangeContent() method in the click_event, it works, but in the _tm_elapsed it doenst work?
using smartHome2011.FramePages;
using System.Timers;
public partial class AuthenticationPage : UserControl
{
private MainWindow _main;
private Storyboard _storyboard;
private Timer _tm = new Timer();
private HomeScreen _homeScreen = new HomeScreen();
public AuthenticationPage(MainWindow mainP)
{
this.InitializeComponent();
_main = mainP;
}
private void ActionButton_Click(object sender, System.EventArgs eventArgs)
{
_main.TakePicture();
identifyBox.Source = _main.source.Clone();
scanningLabel.Visibility = Visibility.Visible;
_storyboard = (Storyboard) FindResource("scanningSB");
//_storyboard.Begin();
Start();
}
private void Start()
{
_tm = new Timer(3000);
_tm.Elapsed += new ElapsedEventHandler(_tm_Elapsed);
_tm.Enabled = true;
}
private void _tm_Elapsed(object sender, ElapsedEventArgs e)
{
((Timer) sender).Enabled = false;
ChangeContent();
//MessageBox.Show("ok");
}
private void ChangeContent()
{
_main.ContentPage.Children.Clear();
_main.ContentPage.Children.Add(_homeScreen);
}
}
Description
You have to use Invoke to ensure that the UI Thread (the thread who has created your Control) will execute that.
1. If you are doing Windows Forms then do this
Sample
private void ChangeContent()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(ChangeContent));
return;
}
_main.ContentPage.Children.Clear();
_main.ContentPage.Children.Add(_homeScreen);
}
2. If you are doing WPF then do this
private void _tm_Elapsed(object sender, ElapsedEventArgs e)
{
((Timer) sender).Enabled = false;
this.Dispatcher.Invoke(new Action(ChangeContent), null);
//MessageBox.Show("ok");
}
More Information
Windows Forms
MSDN - Control.Invoke Method
MSDN - Control.InvokeRequired Property
WPF
MSDN - Dispatcher.Invoke Method
MSDN - Dispatcher Class
The logic executed in the Elapsed event of the Timer is run on a separate thread from the rest of your code. This thread cannot access objects on the main/GUI thread.
This thread should help you find out how to do it: How to update the GUI from another thread in C#?
I suspect you are using a System.Threading.Timer. You can avoid cross thread operation by just using a Windows.Forms timer:
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
That timer uses regular messages and the event occours on the same thread of the UI.
The event to use is no more called "Elapsed", but "Tick" read the doc here: http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx
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.