41

有谁知道如何将多个参数传递给 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);
}

顺便说一句,我用不同的编排器、平衡和端口启动了许多线程。请考虑线程安全。

4

11 回答 11

68

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

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );
于 2009-05-06T18:32:18.273 回答
15

这是一段代码,它使用了这里多次提到的对象数组方法。

    ...
    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);
      ...
    }>
于 2010-04-10T04:01:55.433 回答
11

您需要将它们包装成一个对象。

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

于 2009-05-06T18:31:35.030 回答
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 
   }
}
于 2009-05-06T18:35:42.713 回答
6

JaredPar 答案的 .NET 2 转换

Thread standardTCPServerThread = new Thread(delegate (object unused) {
        startSocketServerAsThread(initializeMemberBalance, arg, 60000);
    });
于 2010-11-18T15:50:23.477 回答
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.
}
于 2012-12-24T11:57:08.443 回答
3

你不能。创建一个包含您需要的参数的对象,然后通过它。在线程函数中,将对象转换回其类型。

于 2009-05-06T18:31:48.197 回答
2

我一直在阅读您的论坛以了解如何做到这一点,并且我以这种方式做到了 - 可能对某人有用。我在构造函数中传递参数,它为我创建将在其中执行我的方法的工作线程 - execute()方法。

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace Haart_Trainer_App

{
    class ProcessRunner
    {
        private string process = "";
        private string args = "";
        private ListBox output = null;
        private Thread t = null;

    public ProcessRunner(string process, string args, ref ListBox output)
    {
        this.process = process;
        this.args = args;
        this.output = output;
        t = new Thread(new ThreadStart(this.execute));
        t.Start();

    }
    private void execute()
    {
        Process proc = new Process();
        proc.StartInfo.FileName = process;
        proc.StartInfo.Arguments = args;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();
        string outmsg;
        try
        {
            StreamReader read = proc.StandardOutput;

        while ((outmsg = read.ReadLine()) != null)
        {

                lock (output)
                {
                    output.Items.Add(outmsg);
                }

        }
        }
        catch (Exception e) 
        {
            lock (output)
            {
                output.Items.Add(e.Message);
            }
        }
        proc.WaitForExit();
        var exitCode = proc.ExitCode;
        proc.Close();

    }
}
}
于 2011-08-06T12:16:41.720 回答
1

您可以获取 Object 数组并将其传递到线程中。经过

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

进入线程构造函数。

yourFunctionAddressWhichContailMultipleParameters(object[])

您已经在 objArray 中设置了所有值。

你需要abcThread.Start(objectArray)

于 2009-05-06T18:31:48.650 回答
0

您可以使用 lambda 表达式对“工作”函数进行 curry:

public void StartThread()
{
    // ...
    Thread standardTCPServerThread = new Thread(
        () => standardServerThread.Start(/* whatever arguments */));

    standardTCPServerThread.Start();
}
于 2009-05-06T18:33:37.693 回答
0

您需要传递一个对象,但如果定义自己的对象以供一次性使用太麻烦,您可以使用Tuple

于 2014-10-23T23:44:17.727 回答