Introduction
This is more or less a reposting of Roy Osherove's posting here. This is a way to add an attribute, [RunInUIThread]
, to every function with which you would normally use the if(InvokeRequired)
pattern. I was looking for a way to not have to copy and paste the same code into all the functions in which I needed multi-threaded capabilities. I happened to come across Roy's article and thought it was the best thing since sliced bread. I think Microsoft should build this into the next .NET release as a standard language feature, so I'm trying to spread the word. Tell your friends, especially if your friends work at Microsoft.
The only thing I have added is unit tests. These demonstrate that InvokeRequired
is needed, showing the manual solution and then the improved solution using the attributes. You'll need NUnit 2.4 to run the unit tests. Technology samples are fine, but tests give me a warm mushy feeling.
Background
The attached sample uses something called AOP, or aspect oriented programming. Without getting into all of the jargon associated with that, the simplest way to think of this example is that AOP gives us method interception capabilities. So, if we can put an attribute on a function, we can associate methods that can be fired before and after specific functions. In those functions, we can then check if we need to use InvokeRequired
if the attribute has been specified, etc. The AOP parts of this example Roy got from the Castle Project. See links for more details.
Using the Code
public delegate void DoThreadedGoodManualType();
private void DoThreadedGoodManual()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new DoThreadedGoodManualType(DoThreadedGoodManual));
return;
}
DoThreadedBad();
}
The generally accepted way of handling multi-threaded operation in WinForm applications is shown above. This works well, but the downside is that you are repeating the InvokeRequired
code and also having to create delegates. What if, instead of the above, we could do this?
[RunInUIThread]
protected virtual void DoThreadedGoodAOP()
{
DoThreadedBad();
}
Ah, the luxury. Well, now you can!
Points of Interest
I had lots of problems trying to test the code because message pumping is done by application.run
in WinForms, which is needed for the InvokeRequried
stuff to work. I tried in vain to get the tests going by just calling controls on separate threads, but alas, you need actual forms to see this in action. So, the unit test is somewhat unconventional in that it is actually launching a WinForm and the WinForm is raising an event, letting the test know that if InvokeRequired
is true
or false
, then the WinForm immediately closes itself so it doesn't just sit there. If anyone can think of a better way, I'd like to see it!
And remember to check out Roy Osherove's blog.
History
- 16-Aug-2007 - Initial version