Does click event handler need to marshal onto main thread?

J

jjkboswell

If I have a form with a button and add a button_Click event handler,
and within that handler I update the form's GUI, do I need to marshal
onto the main thread?

i.e. Do I need to do this:

private void button1_Click(object sender, System.EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(button1_Click),
new object[] {sender, e});
}
else
{
button1.Text = "stuff";
}
}

I think what I'm asking is:
Can form event handlers be on a different thread from the main thread?

Any clarifcation on this appreciated!

Boz
 
M

Mattias Sjögren

i.e. Do I need to do this:

No you don't.

Can form event handlers be on a different thread from the main thread?

It depends on the class that raises the event. They can, but in
general (if you're dealing with a UI component) they don't.



Mattias
 
J

jjkboswell

I guess the problem is that we (the developers) don't know how the UI
component has been implemented. How do I know that the point at which
an event is fired from a UI component is not already on the main
thread? The documentation for the Windows.Forms controls doesn't tell
me. And if I use 3rd party UI components, I have even less confidence
unless its documented.

It would seem that the only safe option is to always do the
InvokeRequired check in ANY method that updates the UI.

I've heard from a colleague that the next DevStudio will support an
attribute on methods that will do the check and marshalling for us.

Boz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top