Reputation: 11
I Have one Form (LoginForm) which has a Background Worker Monitoring a database for new entries.
Then I have another Form (AdminForm) which I need to signal to update its datagrids whenever new data is available.
I could poll the database in the AdminForm too, but considering that LoginForm is already doing some polling, which can be costly, I just want to signal AdminForm to update the DataGridViews with the new data.
You may ask, why is LoginForm doing the polling when youre showing the stuff in the AdminForm? Well, LoginForm is actually processing the data and sending it over the Serial Port :$ heheh. I want it to be able to process the data without having an administrator logged in all the time.
Upvotes: 1
Views: 1859
Reputation: 56707
You could have your background worker signal progress (WorkerReportsProgress
property set to true, then calling ReportProgress
).
In that event handler (OnProgressChanged
), invoke another public event you create that signals receivers that data should be updated. Your admin form could subscribe to that event.
As I'm not quite sure whether the OnProgressChanged
event is invoked in the context of the main thread or in the context of the background worker's thread, I'd suggest you use this.Invoke
when actually doing the UI update.
EDIT
Using OnProgressChanged
and another event, do the following:
In the Form1
class, declare a new event like
public event EventHandler DataChanged;
Also, declare a method that raises the event:
protected void OnDataChanged()
{
if (DataChanged != null)
DataChanged(this, EventArgs.Empty);
}
Then, in the OnProgressChanged
method, call your OnDataChanged
method.
All you need to do now is:
form1.DataChanged += new EventHandler....
You might for example pass the current instance of Form1 to the constructor of Form2 when it is created and attach the event handler in the constructor of Form2. There are other options as well.
EDIT 2
Thinking about it: Why don't you put the polling code into a separate class that provides an event whenever data changes. Then you can attach both Form1 and Form2 to these events. This would make Form2 independant from Form1.
Upvotes: 2