thread con più parametri
-
06-07-2019 - |
Domanda
Qualcuno sa come passare più parametri in una routine Thread.Start?
Ho pensato di estendere la classe, ma la classe Thread C # è sigillata.
Ecco come penso che sarebbe simile al codice:
...
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);
}
A proposito, inizio una serie di thread con diversi orchestratori, bilance e porte. Si prega di considerare anche la sicurezza del thread.
Soluzione
Prova a usare un'espressione lambda per catturare gli argomenti.
Thread standardTCPServerThread =
new Thread(
unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
);
Altri suggerimenti
Ecco un po 'di codice che utilizza l'approccio array di oggetti menzionato qui un paio di volte.
...
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);
...
}>
Devi avvolgerli in un singolo oggetto.
Creare una classe personalizzata per passare i parametri è un'opzione. Puoi anche usare un array o un elenco di oggetti e impostare tutti i tuoi parametri.
Usa il modello 'Task':
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
}
}
Conversione .NET 2 della risposta JaredPar
Thread standardTCPServerThread = new Thread(delegate (object unused) {
startSocketServerAsThread(initializeMemberBalance, arg, 60000);
});
Non puoi. Crea un oggetto che contenga parametri di cui hai bisogno e passalo. Nella funzione thread esegui il cast dell'oggetto al suo 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.
}
Ho letto il tuo forum per scoprire come farlo e l'ho fatto in quel modo - potrebbe essere utile per qualcuno. Passo argomenti nel costruttore che crea per me un thread di lavoro in cui verrà eseguito il mio metodo - execute () metodo.
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();
}
}
}
Puoi prendere l'array Object e passarlo nel thread. Pass
System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters)
Nel costruttore di thread.
yourFunctionAddressWhichContailMultipleParameters(object[])
Hai già impostato tutto il valore in objArray.
devi abcThread.Start(objectArray)
Puoi curry il " lavoro " funzione con un'espressione lambda:
public void StartThread()
{
// ...
Thread standardTCPServerThread = new Thread(
() => standardServerThread.Start(/* whatever arguments */));
standardTCPServerThread.Start();
}
Devi passare un singolo oggetto, ma se è troppo seccante definire il tuo oggetto per un singolo uso, puoi usare una Tupla .