C# 通过 ParameterizedThreadStart 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13776846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:46:31  来源:igfitidea点击:

Pass Parameters through ParameterizedThreadStart

c#multithreading

提问by liamp47

I'm trying to pass parameters through the following:

我正在尝试通过以下方式传递参数:

Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));

Any idea how to do this? I'd appreciate some help

知道如何做到这一点吗?我很感激一些帮助

采纳答案by Tudor

lazyberezovsky has the right answer. I want to note that technically you can pass an arbitrary number of arguments using lambda expression due to variable capture:

lazyberezovsky 有正确的答案。我想指出,由于变量捕获,从技术上讲,您可以使用 lambda 表达式传递任意数量的参数:

var thread = new Thread(
       () => DoMethod(a, b, c));
thread.Start();

This is a handy way of calling methods that don't fit the ThreadStartor ParameterizedThreadStartdelegate, but be careful that you can easily cause a data race if you change the arguments in the parent thread after passing them to the child thread's code.

这是调用不适合ThreadStartorParameterizedThreadStart委托的方法的一种方便的方法,但请注意,如果在将参数传递给子线程的代码后更改父线程中的参数,则很容易导致数据竞争。

回答by Sergey Berezovskiy

Use overloaded Thread.Startmethod, which accepts object (you can pass your custom type or array if you need several parameters):

使用重载Thread.Start方法,它接受对象(如果需要多个参数,可以传递自定义类型或数组):

Foo parameter = // get parameter value
Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
thread.Start(parameter);

And in DoMethodsimply cast argument to your parameter type:

DoMethod简单地将参数强制转换为您的参数类型:

private void DoMethod(object obj)
{
    Foo parameter = (Foo)obj;
    // ...    
}

BTWin .NET 4.0 and above you can use tasks (also be careful with race conditions):

顺便说一句,在 .NET 4.0 及更高版本中,您可以使用任务(也要注意竞争条件):

Task.Factory.StartNew(() => DoMethod(a, b, c));

回答by user1958681

// Parameters to pass to ParameterizedThreadStart delegate
// - in this example, it's an Int32 and a String:
class MyParams
{
    public int A { get; set; }
    public string B { get; set; }

    // Constructor
    public MyParams(int someInt, string someString)
    {
        A = someInt;
        B = someString;
    }
}

class MainClass
{
    MyParams ap = new MyParams(10, "Hello!");
    Thread t = new Thread(new ParameterizedThreadStart(DoMethod));
    t.Start(ap); // Pass parameters when starting the thread
}

回答by Lorenz Lo Sauer

Another way to archive what you want, is by returning a delegate within your function / method. Take the following example:

另一种归档你想要的东西的方法是在你的函数/方法中返回一个委托。以下面的例子为例:

class App
{
  public static void Main()
  {
     Thread t = new Thread(DoWork(a, b));
     t.Start();
     if (t.IsAlive)
     {
         t.IsBackground = true;
     }
  }

  private static ThreadStart DoWork(int a, int b)
  {
      return () => { /*DoWork*/ var c = a + b; };
  }

}

回答by Fly Rose

new Thread(() => { DoMethod(a, b, c); }).Start();

or

或者

new Thread(() => DoMethod(a, b, c)).Start();

回答by Peter Henry

Instead of creating a class to pass in multiple parameters as @user1958681 has done, you could use anonymous types, then just use the dynamic typing to extract your parameters.

您可以使用匿名类型,而不是像 @user1958681 那样创建一个类来传递多个参数,然后只需使用动态类型来提取参数。

class MainClass
{
    int A = 1;
    string B = "Test";

    Thread ActionThread = new Thread(new ParameterizedThreadStart(DoWork));    
    ActionThread.Start(new { A, B});
}

Then in DoWork

然后在 DoWork 中

private static void DoWork(object parameters)
{
   dynamic d = parameters;

    int a = d.A;
    string b = d.B;
 }