Many times i am using code like this:
public static void ExecuteMethod1InThread(string msg)
{
Thread t = new Thread(
new ThreadStart(
delegate
{
log(msg);
}));
t.IsBackground = true;
t.Start();
t.Join();
}
If you notice i am calling a method in a separate thread hoping it would be helpful in performance.
But I am wondering if it is possible to give the method name and parameters dynamically and have it execute it rather than creating blocks of code like above for every method call.
I know we could use reflection but it will affect the performance is my understanding.
I have also heard about anonymous delegates but i am not sure how they work.
Just wondering if anyone could enlighten.
(Read to the bottom for a crucial point!)
Well, you’re already using an anonymous method. You can keep using C# 2.0 and make the code somewhat shorter like this:
Or you could use a lambda expression from C# 3:
Now you can make this simpler for calling different methods like this:
You’d then call this with:
(for example).
Alternatively, you could change it to just take a ThreadStart to start with:
and call it like this:
This isn’t quite equivalent, however, due to when various expressions are evaluated. In particular, doing this in a loop could cause the problems Eric Lippert describes here.
Important point
However, what you’ve currently got will hurt performance. You’re starting a new thread (rather than using the thread-pool) and then you’re waiting for the thread to finish. This is effectively calling the
logmethod synchronously – how can that help performance?