Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating UI thread (textbox) via C#

Business Intelligence guy here with enough C# under my belt to be dangerous.

I’ve built a homebrew winforms application that essentially executes a command-line tool in a loop to “do stuff”. Said stuff may complete in seconds or minutes. Normally I will need to execute the tool once for each row sitting in a DataTable.

I need to redirect the output of the command-line tool and display it in “my” app. I’m attempting to do so via a text box. I’m running into issues around updating the UI thread that I can’t get straightened out on my own.

To execute my command-line tool, I’ve borrowed code from here: How to parse command line output from c#?

Here is my equivalent:

        private void btnImport_Click(object sender, EventArgs e)
        {
           txtOutput.Clear();
            ImportWorkbooks(dtable);

        }


        public void ImportWorkbooks(DataTable dt)
        {

            ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
            cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.CreateNoWindow = false;

            Process cmdProcess = new Process();
            cmdProcess.StartInfo = cmdStartInfo;
            cmdProcess.ErrorDataReceived += cmd_Error;
            cmdProcess.OutputDataReceived += cmd_DataReceived;
            cmdProcess.EnableRaisingEvents = true;
            cmdProcess.Start();
            cmdProcess.BeginOutputReadLine();
            cmdProcess.BeginErrorReadLine();

            //Login
            cmdProcess.StandardInput.WriteLine(BuildLoginString(txtTabCmd.Text, txtImportUserName.Text, txtImportPassword.Text, txtImportToServer.Text)); 


            foreach (DataRow dr in dt.Rows)
            {
                   cmdProcess.StandardInput.WriteLine(CreateServerProjectsString(dr["Project"].ToString(), txtTabCmd.Text));

                //Import Workbook

                cmdProcess.StandardInput.WriteLine(BuildPublishString(txtTabCmd.Text, dr["Name"].ToString(), dr["UID"].ToString(),dr["Password"].ToString(), dr["Project"].ToString()));
            }
            cmdProcess.StandardInput.WriteLine("exit");   //Execute exit.
            cmdProcess.EnableRaisingEvents = false;
            cmdProcess.WaitForExit();
        }


private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
        {
            //MessageBox.Show("Output from other process");
            try
            {
        // I want to update my textbox here, and then position the cursor 
        // at the bottom ala:

                StringBuilder sb = new StringBuilder(txtOutput.Text);
                sb.AppendLine(e.Data.ToString());
                txtOutput.Text = sb.ToString();
                this.txtOutput.SelectionStart = txtOutput.Text.Length;
                this.txtOutput.ScrollToCaret();


            }
            catch (Exception ex)
            {
                 Console.WriteLine("{0} Exception caught.", ex);

            }

        }

Referencing txtOuput.text when I instantiate my StringBuilder in cmd_DataReceived () neatly causes the app to hang: I’m guessing some sort of cross-thread issue.

If I remove the reference to txtOuput.text in StringBuilder and continue debugging, I get a cross-thread violation here:

txtOutput.Text = sb.ToString();

Cross-thread operation not valid: Control 'txtOutput' accessed from a thread other than the thread it was created on.

OK, not surprised. I assumed cmd_DataReceived is running on another thread since I’m hitting it as the result of doing stuff after a Process.Start() …and if I remove ALL references to txtOuput.Text in cmd_DataReceived() and simply dump the command-line text output to the console via Console.Write(), everything works fine.

So, next I’m going to try standard techniques for updating my TextBox on the UI thread using the information in http://msdn.microsoft.com/en-us/library/ms171728.aspx

I add a delegate and thread to my class:

delegate void SetTextCallback(string text);
// This thread is used to demonstrate both thread-safe and
// unsafe ways to call a Windows Forms control.
private Thread demoThread = null;

I add a procedure to update the text box:

 private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.txtOutput.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.txtOutput.Text = text;
        }
    }

I add another proc which calls the thread-safe one:

 private void ThreadProcSafe()
    {
       // this.SetText(sb3.ToString());
        this.SetText("foo");

    }

...and finally I call this mess within cmd_DataReceived like this:

private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
    //MessageBox.Show("Output from other process");
    try
    {

        sb3.AppendLine(e.Data.ToString());

        //this.backgroundWorker2.RunWorkerAsync();
        this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe));
        this.demoThread.Start();
        Console.WriteLine(e.Data.ToString());

    }
    catch (Exception ex)
    {
         Console.WriteLine("{0} Exception caught.", ex);


    }

}

…When I run this text, the textbox sits there dead as a doornail, not getting updated. My console window continues to update. As you can see, I tried simplifying things a bit just by getting the textbox to display "foo" vs. the real output from the tool - but no joy. My UI is dead.

So what gives? Can't figure out what I'm doing wrong. I'm not at all married to displaying results in a textbox, btw - I just need to be able to see what's going in inside the application and I'd prefer not to pop up another window to do so.

Many thanks.

like image 724
Russell Christopher Avatar asked Nov 25 '11 13:11

Russell Christopher


2 Answers

I think the issue is in this line:

cmdProcess.WaitForExit(); 

It's in the method ImportWorkbooks which is called from the Click event method of btnImport. So your UI thread is blocked until the background process is completed.

like image 113
Fischermaen Avatar answered Sep 28 '22 12:09

Fischermaen


You're calling ImportWorkbooks from the UI thread. Then, in this method, you're calling "cmdProcess.WaitForExit()". So basically you're blocking the UI thread until the process has finished executing. Execute ImportWorkbooks from a thread and it should work, or remove the WaitForExit and use the process' "Exited" event instead.

like image 32
Kevin Gosse Avatar answered Sep 28 '22 10:09

Kevin Gosse