How to detect a control being invalidated?
I'm implementing producer/consumer problem. the code looks like this:
void producer()
{
// produce item
// update some control in form
}
void consumer()
{
// consume item
// update some control in form
}
producer and consumer methods are executed in different threads from the one that created my form, so I can't update controls in form. I tried following code:
void producer()
{
// produce item
// put the work to be done in a queue
this.Invalidate();
}
void consumer()
{
// consume item
// put the work to be done in a queue
this.Invalidate();
}
So now I have to detect if the form has been invalidated. I looked in Form's event list, and the best thing I could find was paint event. I put the code that got the job done, and it works fine. The problem is I somehow doub开发者_开发百科t I've done this the right way although it works. I think paint is not the right place to do the job, as what I'm doing it not just painting. I was wondering if there's a better way to do this.
Edit -- Snippet for Invalidated event handler not working
public Form1()
{
InitializeComponent();
this.Invalidated += InvalidateEventHandler;
}
void producer(object o)
{
// produce
// put work in queue
this.Invalidate();
}
public void InvalidateEventHandler(object sender, InvalidateEventArgs e)
{
// Do Stuff to form -- Where exception raises
}
Invalidate is intended to trigger a Paint.
What you need is to Control.Invoke()
your own refresh method on he form.
Edit:
Your non-GUI threads should not even call Invalidate(), they can't touch the GUI.
You can write your own ProcessData() form-method and from the Prod/Cons call mainForm.Invoke(ProcessData)
Then ProcessData()
is responsible for thread-safe access to the data and for Invalidating the GUI
You can try to use new
keyword to make your own implementation of Invalidate
public new void Invalidate()
{
// place your logic here
base.Invalidate();
}
Aslo Form has Invalidated event wich is triggered after Ivalidate ends
EDIT:
public void InvalidateEventHandler(object sender, InvalidateEventArgs e)
{
anotherForm.Invoke(new Action(() =>
{
// Do Stuff to form -- Where exception raises
}));
}
精彩评论