create threadstart with reflection  
Author Message
caligula





PostPosted: .NET Base Class Library, create threadstart with reflection Top

hi,
i want to run a method in a new thread. the problem is that i dont have the type of class that hast the method, so i should use reflection.
Does anyone know how to give method to execute to threadstart class with reflection
Actually the code for normal condition (withoud reflection) whould be something like this:

ThreadStart threadStart = new ThreadStart(SomeFunction)

here i want to get SomeFunction with reflection.
thnx in advanse.



.NET Development8  
 
 
TaylorMichaelL





PostPosted: .NET Base Class Library, create threadstart with reflection Top

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