具有多个参数的线程

Luc*_*s B 37 .net c# parameters multithreading thread-safety

有谁知道如何将多个参数传递给Thread.Start例程?

我想扩展类,但C#Thread类是密封的.

以下是我认为代码的样子:

...
    Thread standardTCPServerThread = new Thread(startSocketServerAsThread);

    standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000);
...
}

static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port)
{
  startSocketServer(orchestrator, memberBalances, arg, port);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我用不同的协调器,天平和端口启动了许多线程.请考虑线程安全.

Jar*_*Par 63

尝试使用lambda表达式来捕获参数.

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );
Run Code Online (Sandbox Code Playgroud)

  • 这是安全的 - 有警告.但是,如果你在调用之后立即调整变量,它可能会产生一些奇怪的副作用,因为你是通过引用有效地传递变量的. (7认同)
  • 因为@Reed Copsey 解释的不做 :for(int i = 0; i &lt; howMany; i++) { Thread t = new Thread(unused =&gt; startSocketServerAsThread( x, y, i) ); t.开始(); }. 使用“代理”,如 int toPass = i; (2认同)

小智 12

这里有一些代码使用了这里提到的对象数组方法几次.

    ...
    string p1 = "Yada yada.";
    long p2 = 4715821396025;
    int p3 = 4096;
    object args = new object[3] { p1, p2, p3 };
    Thread b1 = new Thread(new ParameterizedThreadStart(worker));
    b1.Start(args);
    ...
    private void worker(object args)
    {
      Array argArray = new object[3];
      argArray = (Array)args;
      string p1 = (string)argArray.GetValue(0);
      long p2 = (long)argArray.GetValue(1);
      int p3 = (int)argArray.GetValue(2);
      ...
    }>
Run Code Online (Sandbox Code Playgroud)


Ree*_*sey 11

您需要将它们包装到单个对象中.

创建自定义类来传递参数是一种选择.您还可以使用数组或对象列表,并在其中设置所有参数.


Fre*_*els 7

使用'任务'模式:

public class MyTask
{
   string _a;
   int _b;
   int _c;
   float _d;

   public event EventHandler Finished;

   public MyTask( string a, int b, int c, float d )
   {
      _a = a;
      _b = b;
      _c = c;
      _d = d;
   }

   public void DoWork()
   {
       Thread t = new Thread(new ThreadStart(DoWorkCore));
       t.Start();
   }

   private void DoWorkCore()
   {
      // do some stuff
      OnFinished();
   }

   protected virtual void OnFinished()
   {
      // raise finished in a threadsafe way 
   }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

.NET 2转换JaredPar的答案

Thread standardTCPServerThread = new Thread(delegate (object unused) {
        startSocketServerAsThread(initializeMemberBalance, arg, 60000);
    });
Run Code Online (Sandbox Code Playgroud)


Muh*_*hir 5

void RunFromHere()
{
    string param1 = "hello";
    int param2 = 42;

    Thread thread = new Thread(delegate()
    {
        MyParametrizedMethod(param1,param2);
    });
    thread.Start();
}

void MyParametrizedMethod(string p,int i)
{
// some code.
}
Run Code Online (Sandbox Code Playgroud)