Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6848069
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T00:49:21+00:00 2026-05-27T00:49:21+00:00

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

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T00:49:22+00:00Added an answer on May 27, 2026 at 12:49 am

    one of the reasons you text box doesn’t update is because you don’t pass the string to your SetText method.

    You don’t need to create a thread.
    Your implementation will of SetText will handle passing the call to from the worker thread (where cmd_DataReceived is called) to the UI thread.

    Here is what I suggest you do:

    private void cmd_DataReceived(object sender, DataReceivedEventArgs e)
    {
        //MessageBox.Show("Output from other process");
        try
        {
    
    
            string str = e.Data.ToString();
            sb3.AppendLine(str);
            SetText(str); //or use sb3.ToString if you need the entire thing   
    
            Console.WriteLine(str);
    
        }
        catch (Exception ex)
        {
             Console.WriteLine("{0} Exception caught.", ex);
    
    
        }
    
    }
    

    Also, you are blocking the UI thread as @Fischermaen mentioned when you call WaitForExit, you don’t need it.

    I would also suggest that you run ImportWorkbooks on a worker thread like so:
    (if you do this you can leave the call to WaitForExit)

    private void btnImport_Click(object sender, EventArgs e)
    {
         txtOutput.Clear();
         ThreadPool.QueueUserWorkItem(ImportBooksHelper, dtTable);
    }
    
    private ImportBooksHelper(object obj)
    {
        DataTable dt = (DataTable)obj;
        ImportWorkbooks(dtable);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm a Business Intelligence guy slowly and painfully getting re-ramped on web-dev. Haven't really
I am making some small business intelligence applications/tools that need to talk to other
Is there a framework to unit test applications categorized under Business Intelligence - especially
When building a report in Business Intelligence Studio 2008, I've noticed that the hide/show
Is business intelligence a buzzword that has no real meaning to software developers, or
In Business Intelligence Developer Studio, I'm wondering why one would want to create a
I opened up Business Intelligence Design Studio (BIDS) the other day. Since then my
I'm currently researching SQL Server 2008 as a business intelligence solution, and currently looking
I'm scheduling CSVs to a remote FTP via a business intelligence tool once a
I have a SSIS package built in Business Intellegience Development Studio which have both

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.