c# - C# : How can I pass a function name to another function to start a new thread? 中的多线程

标签 c# .net multithreading oop

我在我的 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/

相关文章:

c# - 将 C# Console.Write* 与 AWS Lambda 结合使用

c# - 为什么按 ref 返回对集合元素不起作用?

.net - 如何取消任何当前的 Parallel.ForEach 并重新开始

.net - NUnit 断言枚举值包含标志

java - Thread中List的内存范围

c# - 有没有办法将 SelectMany 用于字典

c# - 如何使此类更易于重用? (具体例子里面)

linux - 负责配置进程数和线程数的Linux配置参数有哪些?

java - 如何让 Java 线程通知自己?

c# - 使用 C# 从服务器读取数据库名称