Geeks With Blogs
Freestyle Coding Programming in the Real World

I just stumbled on a cool trick that I had to share. I wanted to dynamically find and call initialization code. This led me to the use of attributes. Of course, once we find our method, we need to call it by using Method.Invoke( object, object).

The problem was that most of the initialization code didn't touch each other. As such, I wanted to wrap the calls into threads. However, thread targets usually have to take either no parameters or one object. However, Invoke requires 2 parameters.

The solution was to wrap or call in a anonymous function:

public class InitializeAttribute: Attribute {
public bool ThreadSafe {
private set;
public InitializeAttribute( bool p_ThreadSafe ) {
ThreadSafe = p_ThreadSafe;
public class MainWindow : Window {
public MainWindow() {
List<Thread> _CreatedThreads = new List<Thread>();
MethodInfo[] _Methods = this.GetType().GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
foreach( MethodInfo _Method in _Methods ) {
Attribute[] _Attributes = Attribute.GetCustomAttributes( _Method, typeof( InitializeAttribute ), false );
foreach( InitializeAttribute _Token in _Attributes ) {
if( _Token.ThreadSafe ) {
Thread _NewThread = new Thread( () => _Method.Invoke( this, null ) );
_CreatedThreads.Add( _NewThread );
} else {
_Method.Invoke( this, null );
foreach( Thread _Thread in _CreatedThreads )
[Initialize( true )]
private void InitializeSubsection() {
// Do Thread Safe initialization here
This worked like a champ, and it made me deliriously happy. Thus, I am now sharing it with you. Go forth, and be happy. Posted on Thursday, July 12, 2012 1:11 PM .NET , C# , Reflection | Back to top

Comments on this post: Reflective Threads

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Chris Gardner | Powered by: