fil avec plusieurs parameters

Est-ce que quelqu’un sait comment passer plusieurs parameters dans une routine Thread.Start?

J’ai pensé à étendre la classe, mais la classe C # Thread est scellée.

Voici à quoi je pense que le code ressemblerait:

... Thread standardTCPServerThread = new Thread(startSocketServerAsThread); standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000); ... } static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List memberBalances, ssortingng arg, int port) { startSocketServer(orchestrator, memberBalances, arg, port); } 

En passant, je démarre un certain nombre de threads avec différents orchestrateurs, balances et ports. S’il vous plaît envisager la sécurité du fil aussi.

Essayez d’utiliser une expression lambda pour capturer les arguments.

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

Vous devez les envelopper dans un seul object.

Faire une classe personnalisée pour passer vos parameters est une option. Vous pouvez également utiliser un tableau ou une liste d’objects et définir tous vos parameters dans ce contexte.

Voici un peu de code qui utilise l’approche du tableau d’objects mentionnée ici plusieurs fois.

  ... ssortingng 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; ssortingng p1 = (ssortingng)argArray.GetValue(0); long p2 = (long)argArray.GetValue(1); int p3 = (int)argArray.GetValue(2); ... }> 

Utilisez le modèle ‘Task’:

 public class MyTask { ssortingng _a; int _b; int _c; float _d; public event EventHandler Finished; public MyTask( ssortingng 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 } } 

Conversion .NET 2 de JaredPar answer

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

Tu ne peux pas. Créez un object contenant les parameters dont vous avez besoin, et passez le test. Dans la fonction thread, convertissez l’object en son type.

J’ai lu votre forum pour savoir comment le faire et je l’ai fait de cette façon – cela pourrait être utile pour quelqu’un. Je passe des arguments dans le constructeur qui crée pour moi un thread de travail dans lequel sera exécutée ma méthode méthode – 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 ssortingng process = ""; private ssortingng args = ""; private ListBox output = null; private Thread t = null; public ProcessRunner(ssortingng process, ssortingng 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(); ssortingng 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(); } } } 
 void RunFromHere() { ssortingng param1 = "hello"; int param2 = 42; Thread thread = new Thread(delegate() { MyParamesortingzedMethod(param1,param2); }); thread.Start(); } void MyParamesortingzedMethod(ssortingng p,int i) { // some code. } 

Vous pouvez prendre Object array et le transmettre au fil. Passer

 System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

Dans le constructeur de thread.

 yourFunctionAddressWhichContailMultipleParameters(object[]) 

Vous avez déjà défini toutes les valeurs dans objArray.

vous devez abcThread.Start(objectArray)

Vous pouvez curry la fonction “travail” avec une expression lambda:

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

Vous devez passer un seul object, mais s’il est trop fastidieux de définir votre propre object pour une utilisation unique, vous pouvez utiliser un tuple .