【问题标题】:How to put a method with one parameter into the Thread C# [duplicate]如何将具有一个参数的方法放入线程 C# [重复]
【发布时间】:2012-11-15 03:04:10
【问题描述】:

可能重复:
C# ThreadStart with parameters

如何将具有一个参数的方法放入线程 C#。

例子:

Thread thread = new Thread(SoundInputThread.getSomething(hz));
                 thread.Start();
                 for (int i = 0; i < 5; i++) {
                     Console.WriteLine();
                     Thread.Sleep(1000);
                 }


     public static void getSomething(int hz) {
            hz = 100;
            Console.WriteLine();
        }

【问题讨论】:

  • 您是否遇到任何错误?如果有,它们是什么?
  • 必须通过在 ThreadStart 或 ParameterizedThreadStart 对象中的paasing 来创建线程对象。

标签: c# multithreading


【解决方案1】:

您可以按如下方式捕获该值:

Thread thread = new Thread(() => {
   getSomething(hz);
});
thread.Start();

【讨论】:

  • 与参数化线程启动相比,它的主要优点是您不需要强制转换(或装箱)参数,而且您可以拥有多个参数。
【解决方案2】:

您需要使用 Thread 的重载构造函数,它采用 ParameterizedThreadStart 它将允许将参数传递给线程方法。在该方法中,您可以将对象返回到您的类型。

thread = new Thread(new ParameterizedThreadStart(getSomething));
thread.Start(2);

public static void getSomething(object obj) {
      int i = (int)obj;
}

【讨论】:

  • 那么我想: int a = (int)obj; ?
  • 是的,我已经更新了。
  • 好吧,最后再来一个...如何通过引用而不是值传递一个 int?
  • 你可以使用类型转换来像(object)i这样的对象
  • @Robert 你没有,你传递一个对包含整数的对象的引用,然后从另一个位置修改该对象。无论如何,这确实是一个单独的问题。
猜你喜欢
  • 2011-07-30
  • 2013-06-18
  • 1970-01-01
  • 2013-10-27
  • 2022-11-05
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多