Search code examples
c#winformsruntimelocked

C# Windows form application is locked during runtime


I'm new to C# and i have a problem ... when i run my windows form application and press start button, during runtime i can't do anything with the form (close, minimize, move, ...) but when it's done i can close the form.
What should i do to solve it?

enter image description here

using System;
using System.Threading;
using System.Windows.Forms;


namespace WindowsFormsApplication10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void c1Button1_Click(object sender, EventArgs e)
        {
            for ( int i = 0; i < 100; i++)
            {

                c1RadialGauge1.Value = i;
                textBox1.Text = i.ToString();
                textBox1.Update();
                c1Gauge1.Refresh();
                Thread.Sleep(100);

            }

        }
    }
}

Solution

  • Since your button handler is running in the UI thread until it is finished, your UI blocks and you can't do anything else with that.

    One solution to that would be to make the handler async and use await a Task.Delay() instead of using Thread.Sleep():

    private async void c1Button1_Click(object sender, EventArgs e)
    {
        c1Button1.Enabled = false; // avoid multiple clicks
        for ( int i = 0; i < 100; i++)
        {
            c1RadialGauge1.Value = i;
            textBox1.Text = i.ToString();
            textBox1.Update();
            c1Gauge1.Refresh();
            await Task.Delay(100);
        }
        c1Button1.Enabled = true; // allow further clicks
    }
    

    The compiler translates this code into a state machine. At the await keyword, the control flow is returned to the caller (the UI) and resumed when Task.Delay() has finished. So while Task.Delay() runs, the UI thread has time to react on other events (e.g. user interaction).

    I added two lines to disable the button while the whole thing is running, so that the user can't start this several times.

    But this is only possible using .NET 4.5 or newer. Read this for more information about async/await.

    If you have to use an older .NET framework, you may use a BackgroundWorker instead.