I am using multithreading in my C# code as follow:
Thread startThread;
public void NewThread()
{
ThreadStart starter = delegate { foo(); };
startThread = new Thread(starter);
startThread.Start();
}
private void foo()
{
//do some work
}
And then in my application I call NewThread()to run the new thread.
But now I am having lots of threads on each class and each one has a NewThread() for itself, I was thinking of moving this to a static Util class and pass it the function name each time I want a new thread on that function.
Do you know how this the best way of doing it, if yes how can I pass the function name as a parameter to it?
Well, since the method is private, does it make sense for the caller to know the method name? If it was public, you could pass the method in:
public void NewThread(Action task)
{
ThreadStart starter = delegate { task(); };
startThread = new Thread(starter);
startThread.Name = task.Method.Name;
startSpoolerThread.Start();
}
public void foo()
{
//do some work
}
NewThread(obj.foo);
However, for a private method, I suspect an enum/switch is the best option...
NewThread(TasktType.Foo);
Alternatively, you can get the method via reflection...
public void NewThread(string name)
{
MethodInfo method = GetType().GetMethod(name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
ThreadStart starter = delegate { method.Invoke(this, null); };
// etc (note: no point using Delegate.CreateDelegate for a 1-call usage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With