c# - 在 C# 线程中传递参数化方法时出错

标签 c# multithreading

我在 A 类中有一个方法,我想通过传递参数在 B 类中线程启动它。

class ClassA
{
  public void MethodA(string par1, int par2)
  {
    Console.WriteLine("Parameter " + par1 + " is passed with value " + par2);
  }
}

class ClassB
{
  public static void Main(string[] args)
  {
    ClassA obj = new ClassA();
    Thread workerThread = new Thread(new ParameterizedThreadStart(obj.MethodA));
    workerThread.Start("book",5);
  }
}

但是当我执行代码时,它给了我一个错误 `

No overload for 'MethodA' matches delegate 'System.Threading.ParameterizedThreadStart

问题是什么?

最佳答案

试试这个...

void Main()
{
    ClassA obj = new ClassA();
    Thread thread = new Thread(() => obj.MethodA("Param1", 2));
    thread.Start();
    thread.Join();
}


class ClassA
{
    public void MethodA(string par1, int par2)
    {
        Console.WriteLine("Parameter " + par1 + " is passed with value " + par2);
    }
}

问题...

正如其他人已经说过的,你的参数太多了......

除此之外,您也不需要等待线程完成其操作。

您在上面看到的称为lambda表达式,基本上是一个匿名函数,您可以通过多种方式组合它,上面只是一个示例。

这是另一个...

void Main()
{
    ClassA obj = new ClassA();
    Thread thread = new Thread(()=> 
    {
        Console.WriteLine ("About to execute MethodA");
        obj.MethodA("test", 2);
        Console.WriteLine ("Executed Method A");
    });
    thread.Start();
    thread.Join();
}


class ClassA
{
    public void MethodA(string par1, int par2)
    {
        Console.WriteLine("Parameter " + par1 + " is passed with value " + par2);
    }
}

如果您需要进一步帮助,请告诉我

关于c# - 在 C# 线程中传递参数化方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35522933/

相关文章:

c# - HttpListener 服务器返回错误 : (503) Service Unavailable

c# - 使用 System.Text.Json.Serialization 将动态对象转换为 json 时抛出异常

java - 试图停止执行2秒钟

c# - 在 WPF Calendar 控件中设置显示月份

c# - 如何以编程方式获取 Excel 支持的最早日期

c# - 如何在 excel 中定义色标条件格式

multithreading - Clojure:阻止使用原子?

Java Callable 线程 Swing gui

java - 如何确定 Java 进程的 CPU 利用率为 100%

java - 为什么 JVM 不等待用户应用程序生成的守护线程?