Follow @RoyOsherove on Twitter

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?

I'm In!

Ingo Rocks Too