Click here to Skip to main content
6,594,088 members and growing! (16,444 online)
Email Password   helpLost your password?
Languages » C# » General     Advanced

Getting Around InvokeRequired Without Copy and Paste

By Paul B.

Instead of copying and pasting the same if(InvokeRequired) logic in every multithreaded function, use attributes to make code cleaner, its centralize logic and make it self documenting.
C# 2.0, C# 3.0.NET 2.0, Win2K, WinXP, Win2003, Vista, .NET 3.0, WinForms, VS2005, Dev
Posted:17 Aug 2007
Views:28,209
Bookmarked:43 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
12 votes for this article.
Popularity: 5.09 Rating: 4.72 out of 5

1

2
1 vote, 8.3%
3
1 vote, 8.3%
4
10 votes, 83.3%
5

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();
/// <summary>

/// This is good behavior, but this manual invoke required junk to be

/// done every time

/// </summary>

private void DoThreadedGoodManual()
{
    if (this.InvokeRequired)
    {
        // Pass the same function to BeginInvoke, but the call would come on

        // the correct thread and InvokeRequired will be false.

        this.BeginInvoke(new DoThreadedGoodManualType(DoThreadedGoodManual));
        return;
    }
    DoThreadedBad(); //now we can do our normal functionality with no worries

}

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Paul B.


Member
I've been a software developer since 1996 and have enjoyed C# since 2003. I have a Bachelor's degree in Computer Science and for some reason, a Master's degree in Business Administration. I currently work at a hedge fund in Dallas, TX.
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
GeneralVery good Pinmemberfly90415:51 5 Apr '09  
GeneralVery nice, but one comment PinmemberMember 35976533:40 1 Apr '09  
GeneralRe: Very nice, but one comment PinmemberMember 35976533:55 1 Apr '09  
GeneralRe: Very nice, but one comment PinmemberMember 35976536:15 1 Apr '09  
GeneralRe: Very nice, but one comment PinmemberPaul B.6:47 1 Apr '09  
GeneralExcellent Pinmembermanitra23:57 23 Jan '09  
GeneralRe: Excellent PinmemberPaul B.10:15 24 Jan '09  
General:( Pinmembermikker_1232:54 25 Aug '07  
GeneralRe: :( PinmemberPaul B.6:04 25 Aug '07  
GeneralNice but... PinmemberIgor Velikorossov15:10 19 Aug '07  
GeneralRe: Nice but... PinmemberPaul B.16:33 19 Aug '07  
GeneralRe: Nice but... PinmemberIgor Velikorossov16:41 19 Aug '07  
GeneralRe: Nice but... PinmemberPaul B.4:22 20 Aug '07  
GeneralRe: Nice but... PinmemberPaul B.6:21 20 Aug '07  
GeneralAwesome and awesome Pinmemberreinux11:29 19 Aug '07  
GeneralRe: Awesome and awesome PinmemberPaul B.11:38 19 Aug '07  
GeneralEeeexcellent PinmemberGuido_d3:44 18 Aug '07  
GeneralParameters PinmemberRoguer122:44 17 Aug '07  
GeneralRe: Parameters PinmemberPaul B.3:45 18 Aug '07  
GeneralRe: Parameters PinmemberPaul B.3:48 18 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Aug 2007
Editor: Sean Ewington
Copyright 2007 by Paul B.
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project