Pergunta

Alguém sabe como passar vários parâmetros em uma rotina Thread.Start?

pensei em estender a classe, mas a classe # Tópico C está selado.

Aqui está o que eu acho que o código ficaria assim:

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

BTW, eu começo uma série de tópicos com diferentes Orchestrators, saldos e portos. Por favor, considere a segurança do thread também.

Foi útil?

Solução

Tente usar uma expressão lambda para capturar os argumentos.

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

Outras dicas

Aqui está um pouco de código que usa a abordagem matriz de objeto mencionado aqui algumas vezes.

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

Você precisa envolvê-los em um único objeto.

Fazendo uma classe personalizada para passar em seus parâmetros é uma opção. Você também pode usar uma matriz ou lista de objetos e definir todos os seus parâmetros nisso.

padrão Use a 'tarefa':

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

.NET 2 conversão de resposta JaredPar

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

Você não pode. Criar um objeto que contém parâmetros que você precisa, e passe é isso. Na função de rosca lançar o objeto de volta para o seu tipo.

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

Estive lendo seu fórum para descobrir como fazê-lo e eu fiz isso dessa maneira - pode ser útil para alguém. Eu passar argumentos no construtor que cria para mim trabalhar segmento em que será executado o meu método -. execute () método

 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();

    }
}
}

Você pode tomar matriz de objectos e passá-lo no segmento. Passe

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

Em construtor fio.

yourFunctionAddressWhichContailMultipleParameters(object[])

Você já definido todo o valor em objArray.

você precisa abcThread.Start(objectArray)

Você poderia caril a função de "trabalho" com uma expressão lambda:

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

    standardTCPServerThread.Start();
}

Você precisa passar um único objeto, mas se é demasiado incómodo para definir seu próprio objeto para um único uso, você pode usar um Tuple .

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top