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

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

有帮助吗?

解决方案

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

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );

其他提示

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

    ...
    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);
      ...
    }>

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

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

使用'任务'模式:

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 
   }
}

JaredPar的.NET 2转换回答

Thread standardTCPServerThread = new Thread(delegate (object unused) {
        startSocketServerAsThread(initializeMemberBalance, arg, 60000);
    });

你做不到。创建一个包含所需params的对象,并传递它。在线程函数中,将对象强制转换为其类型。

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.
}

我一直在阅读你的论坛,了解如何做到这一点,我这样做了 - 可能对某些人有用。我在构造函数中传递参数,它为我创建了一个工作线程,其中将执行我的方法 - 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();

    }
}
}

您可以使用Object数组并在线程中传递它。通过

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

进入线程构造函数。

yourFunctionAddressWhichContailMultipleParameters(object[])

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

你需要 abcThread.Start(objectArray)

你可以讨论“工作”。具有lambda表达式的函数:

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

    standardTCPServerThread.Start();
}

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top