Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in C#: How can I pass a function name to another function to start a new thread?

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?

like image 306
Ali Avatar asked Mar 01 '23 00:03

Ali


1 Answers

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
like image 78
Marc Gravell Avatar answered Mar 03 '23 16:03

Marc Gravell