You don't need to use reflection to actually generate the thread start call but rather you just need to acquire the delegate to invoke. Fortunately this is pretty easy. Let's start with how you'd normally do it.
class SomeClass { public void DoWork ( ) { Debug.WriteLine("Did work"); } }
class Program { static void Main ( string[] args ) { SomeClass cls = new SomeClass(); Thread thread = new Thread(new ThreadStart(cls.DoWork));
thread.Start(); thread.Join(); } }
Skipping the fluff we'll assume that you have an existing instance that you'll reflect against (cls). For this discussion it doesn't really matter how you ultimately got the type and created an instance. What is important is that you'll have (either through a direct call or reflection) the type and instance object to work with. To clarify this I'll remove the SomeClass type and use a generic object. You'll retrieve the desired method, create a delegate from it, cast it to a ThreadStart delegate and then pass it to Thread.
static void Main ( string[] args ) { //Created either directly or through reflection object cls = new SomeClass();
Type type = cls.GetType(); MethodInfo meth = type.GetMethod("DoWork");
ThreadStart start = Delegate.CreateDelegate(typeof(ThreadStart), cls, meth) as ThreadStart; Thread thread = new Thread(start); thread.Start(); thread.Join(); }
If the method is actually static then leave out the second parameter to CreateDelegate.
Michael Taylor - 10/26/06
|