我在我的 C# 代码中使用多线程,如下所示:
Thread startThread;
public void NewThread()
{
ThreadStart starter = delegate { foo(); };
startThread = new Thread(starter);
startThread.Start();
}
private void foo()
{
//do some work
}
然后在我的应用程序中调用 NewThread() 来运行新线程。
但是现在我在每个类上都有很多线程并且每个线程都有一个 NewThread() 自己,我正在考虑将它移动到静态 Util 类并在每次我想要一个新线程时将函数名称传递给它那个函数。
您知道这是最好的方法吗?如果是,我如何将函数名称作为参数传递给它?
最佳答案
既然方法是私有(private)的,调用者知道方法名有意义吗?如果它是公开的,您可以将方法传递给:
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);
但是,对于私有(private)方法,我怀疑枚举/开关是最佳选择...
NewThread(TasktType.Foo);
或者,您可以通过反射获取方法...
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
关于c# - C# : How can I pass a function name to another function to start a new thread? 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/560321/