Wednesday, September 28, 2005

SafeInvoke: Making GUI Thread Programming Easier in C#

John Wood has written a pretty tricky and seemingly very helpful solution to call methods on UI controls easily (as in – much lesser code).

You know the problem: if you want to call a UI component’s method in a thread-safe manner, you must use the Invoke (or BeginInvoke and EndInvoke) method. In addition, you need a delegate and a special method for every such method you call, and then you have to do that again in each project! (I’m not talking about C# 2).

I’ve seen various ways people have tried to work around this painful bit, but I think that John’s looks particularly nice.

Performance-wise, for a single call it may be too expensive since it’s based on Reflection, but in most cases those calls are performed again and again and since he uses a caching mechanism I wouldn’t worry about that.

I’m certainly going to try it out next time I need it!

Ah, I almost forgot, here’s the link:



No comments: