0

As you can see into my code example, when user clicks on Button1, an application starts and program waits until its process name shows up in the processes list.

My "problem" is with the Label1.Text before

Process.Start(@"\application.exe");

Αlthough this.Cursor = Cursors.WaitCursor; works fine, the label doesn't get the updated with the text "Please wait..." while waiting.

What am I doing wrong?

private void Button1_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Do you want to start the application?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        this.Cursor = Cursors.WaitCursor;
        Label1.Text = "Please wait...";

        Process.Start(@"\application.exe");

        Process[] processes;

        do
        {
            processes = Process.GetProcessesByName("applicationname");
            Thread.Sleep(500);
        }
        while (processes.Length == 0);

        this.Cursor = Cursors.Default;
        Label1.Text = "Done!!!";
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Simos Sigma
  • 958
  • 7
  • 29
  • 1
    First, please remove the [tag:visual-studio-2022] tag. It's not relevant to this question. As for the problem, you're holding up the UI thread. UI updates won't get applied until the method is finished and the thread is free again. A quick fix (and usually what I do) would be to put everything on a new thread then [use `BeginInvoke`](https://stackoverflow.com/a/14890338/10601203) to switch back to the UI thread when you need to make changes after it's finished. – Jesse Sep 17 '22 at 08:35
  • 1
    The main thread of your program can only do one thing at a time. It can run that do/while loop *or* it can repaint the label, it can't do both at the same time. A basic workaround is to force it to repaint immediately, add `label1.Update();` – Hans Passant Sep 17 '22 at 08:46
  • 1
    Do beware the bug in this code. It always sleeps for half a second, regardless of how long at actually takes to start the process. Fix that and you may well conclude that you don't need the loop at all. – Hans Passant Sep 17 '22 at 08:53
  • @Jesse can I have an example based on my code so to understand what you mean? – Simos Sigma Sep 17 '22 at 08:56
  • @HansPassant do you mean I have to increase the waiting time or completely remove it? – Simos Sigma Sep 17 '22 at 08:57
  • Anyway I made it using a `BackgroundWorker`. – Simos Sigma Sep 17 '22 at 10:00

0 Answers0