Je ne fournirai pas tout le code, mais un exemple de ce que je veux faire. J'ai ce code pour mettre à jour les éléments GUI à partir d'un processus externe stderr.Comment passer des objets entre threads lors de l'exécution d'un processus System.Diagnostics
Je mis en place mon processus comme celui-ci:
ProcessStartInfo info = new ProcessStartInfo(command, arguments);
// Redirect the standard output of the process.
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.CreateNoWindow = true;
// Set UseShellExecute to false for redirection
info.UseShellExecute = false;
proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;
// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);
proc.Start();
// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
J'ai alors un gestionnaire d'événements
void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
UpdateTextBox(e.Data);
}
}
qui invoque ce qui suit, qui fait référence à un contrôle spécifique zone de texte.
private void UpdateTextBox(string Text)
{
if (this.InvokeRequired)
this.Invoke(new Action<string>(this.SetTextBox), Text);
else
{
textBox1.AppendText(Text);
textBox1.AppendText(Environment.NewLine);
}
}
Ce que je veux est quelque chose comme ceci:
private void UpdateTextBox(string Text, TextBox Target)
{
if (this.InvokeRequired)
this.Invoke(new Action<string, TextBox>(this.SetTextBox), Text, Target);
else
{
Target.AppendText(Text);
Target.AppendText(Environment.NewLine);
}
}
que je peux utiliser pour mettre à jour les différentes zones de texte avec de ce fil, sans avoir à créer une fonction séparée pour chaque commande dans l'interface graphique.
Est-ce possible? (évidemment le code ci-dessus ne fonctionne pas correctement)
Merci.
MISE À JOUR:
private void UpdateTextBox(string Text, TextBox Target)
{
if (this.InvokeRequired)
this.Invoke(new Action<string, TextBox>(this.**UpdateTextBox**), Text, Target);
else
{
Target.AppendText(Text);
Target.AppendText(Environment.NewLine);
}
}
Ce code ne semble travailler maintenant comme je l'ai remarqué une faute de frappe .. est-ce correct à utiliser?
En fait, il semble que cela fonctionne, juste que je n'ai pas changé SetTextBox en UpdateTextBox quand je l'ai copié et collé. – dave
Pourriez-vous expliquer le problème que vous rencontrez? –
Cela fonctionne mais si je mets une pause là-bas et regarde "Cible" dans l'EDI, il dit "'Target.Text' a jeté une exception de type 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException'" – dave