I want to create a small C#-program which has multiple buttons which execute a Powershell script and put the results asynchronously into a textbox. I wanted to do it the following way:
private void Button_Click(object sender, RoutedEventArgs e)
{
var ps1File = @"SomeScript.ps1";
Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "powershell.exe";
proc.StartInfo.Arguments = $"-NoProfile -ExecutionPolicy unrestricted \"{ps1File}\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
var err = "";
tbConsole.Text = "Loading printers ...";
proc.OutputDataReceived += (o, e2) =>
{
if (e2.Data == null) err = e2.Data;
else
{
if (e2.Data == null) err = e2.Data;
else tbConsoleError.AppendText(e2.Data);
}
};
proc.ErrorDataReceived += (o, e2) =>
{
if (e2.Data == null) err = e2.Data;
else tbConsoleError.AppendText(e2.Data);
};
proc.Start();
// and start asynchronous read
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
// wait until it's finished in your background worker thread
proc.WaitForExit();
tbConsole.AppendText("... finished");
}
Now when I hit the button the sript runs but while editing the textboxes it gives me an error that I cannot edit the textbox as it is managed by a different thread.
When I now try to edit my code to use "invoke" and delegate I find that my MainWindow (objet-reference: "this") does not have an "invoke"-method. What am I doing wrong?