Home > front end >  C# winforms, progress bar will freeze on button click event
C# winforms, progress bar will freeze on button click event

Time:11-18

So I have my progress bar in my form as 'Marquee' style so it should continuously run, however when I click my button so that the progress will appear, it is froze and does not move, however if I don't hide the progressbar at the start it will run normally.

I only want it to appear when the button is clicked though, any ideas around this?

    public Form1()
    {
        InitializeComponent();
        progressBar1.Hide();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Show();
        DrawingHandler MyDrawingHandler = new DrawingHandler();
        MyDrawingHandler.GetConnectionStatus();
            try
            {
                Operation.RunMacro("shaftCheck.cs");
                DrawingEnumerator SelectedDrawings = MyDrawingHandler.GetDrawingSelector().GetSelected();
                if (SelectedDrawings.GetSize() == 0)
                {
                    MessageBox.Show("Error, no drawings to export.");
                }
                else
                {
                    Operation.RunMacro("ExportShaft2.cs");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error");
            }
    }
}

CodePudding user response:

The most likely reason is that you are doing some kind of slow operation on the UI thread.

There is in most cases only one UI thread, this is the only thread allowed to update the UI, and this can only do one thing at a time. If you are using the UI thread to do some kind of processing it cannot do other things, like updating your UI.

The solution is to put all processing intensive operation on a background thread. For example with Task.Run. But you will need to ensure any called code does not trigger any UI updates.

If you just have a progress bar as part of the dialog it is fairly easy. But it results in the user being able to do other things while you are doing the processing, so you need to be super-careful that all your code is thread safe.

A safer option is usually to show a modal dialog that prevents the user from doing anything else. This greatly reduces the risk of thread safety issues. Typically it would look something like this:

            var progressForm = new MyProgressForm();
            Task.Run(MyWorkerMethod)
                .ContinueWith(t => progressForm.DialogResult = DialogResult.OK, TaskScheduler.FromCurrentSynchronizationContext());
            progressForm .ShowDialog();

CodePudding user response:

Is there another property in the progressbar that is a better fit for your needs. Winforms Progress Bar Visible true false in this post it looks like you can change the visibility with the Visibility property.

  • Related