Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program doesn't increment progress bar while waiting for thread to exit

I have a c# form app that serves as an UI and executes an external exe. I want to make a progress bar increment until the external exe finishes executing. so i have the following code:

// create thread and Start external process

Thread MyNewThread = new Thread(new ThreadStart(startmodule));
MyNewThread.Start();

            do
            {
                if (progressBar1.Value < 100)
                {
                    progressBar1.Value++;
                }
            } while (MyNewThread.IsAlive); 

            label5.Text = "Status: Done";

// startmodule()
void startmodule()
    {
        ProcessObj = new Process();
        ProcessObj.StartInfo.FileName = ApplicationPath;
        ProcessObj.StartInfo.Arguments = ApplicationArguments;
        ProcessObj.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        ProcessObj.Start();
    }

Instead it fills the bar up instantly and shows "Done" message but the external exe (AppPath) still runs in the background.

Please post some ideas im stuck. i don't know whats wrong. Thank you for your time.

like image 606
sparky Avatar asked Dec 28 '22 10:12

sparky


1 Answers

You cannot make this work, you cannot guess how long the process will take. Set the ProgressBar.Style property to Marquee. Set it Visible property to true when you start the process. Use the Process.Exited event to set it back to false. Like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        progressBar1.Style = ProgressBarStyle.Marquee;
        progressBar1.Visible = false;
    }

    private void ButtonRunProcess_Click(object sender, EventArgs e) {
        var ProcessObj = new Process();
        ProcessObj.SynchronizingObject = this;
        ProcessObj.EnableRaisingEvents = true;
        ProcessObj.Exited += new EventHandler(ProcessObj_Exited);
        ProcessObj.StartInfo.FileName = @"c:\windows\notepad.exe";
        // etc...
        ProcessObj.Start();
        progressBar1.Visible = true;
    }

    void ProcessObj_Exited(object sender, EventArgs e) {
        progressBar1.Visible = false;
    }
}
like image 98
Hans Passant Avatar answered Feb 15 '23 06:02

Hans Passant