UI Threading - A Very Simple Solution - ISerializable - Roy Osherove's Blog

UI Threading - A Very Simple Solution

God loves the simple solutions. It turns out that there is a really simple solution to the problem of working with UI threads.Much simpler then mine. I was given this simple pattern by a guy on the win_tech_off_topic list. Here it is:

"I've read your article, and there is a simple pattern for multi-threaded

UI: in your event, you check the InvokeRequired parameter.

Eg: (this hasn't been anywhere near a compiler)

protected void windowsform_Event(object sender, EventArgs e)

{

if (this.InvokeRequired)

{

this.Invoke(new EventHandler(windowsform_Event), new object[] { sender, e });

return;

}

// do your magic here, and it will always be on the UI thread

}

Best wishes, James Berry"

 

Good one! I've been reading about UI threading in one of the past MSDN issues. The InvokeRequired Property returns true if the thread that reads it is not the UI thread of the control. Simple, elegant. What more could one ask for?

Published Tuesday, May 20, 2003 12:56 PM by RoyOsherove

Comments

Monday, May 19, 2003 8:19 PM by SBC

# re: UI Threading - A Very Simple Solution

Good one Roy. Will check it out with an example.
Monday, May 19, 2003 10:17 PM by Rob Cannon

# re: UI Threading - A Very Simple Solution

It seems like this bit of code would be an ideal thing to be hidden via a custom attribute. There was an MSDN article about writing interceptors a couple of issues ago. I'll have to look it up and see what is possible.
Monday, May 19, 2003 10:23 PM by Royo

# re: UI Threading - A Very Simple Solution

Exactly my thoughts! We'll see who gets there first ... ;)
Tuesday, May 20, 2003 8:46 AM by Addy Santo

# re: UI Threading - A Very Simple Solution

Before diving too deep into interceptors and ContextObjects (and their related side effects such as insanity) take a look at this, it might be close to what you had in mind:

http://www.fawcette.com/vsm/2002_09/magazine/columns/blackbelt/default_pf.asp

-Addy