-1

I have a button on a windows form application that when pressed runs two functions that are in different classes. The processing time takes 10 seconds or so and I would like to run a progress bar simply as aesthetic feedback for the user so they know something is happening. It does not need to actually progress as the work is done. The problem is it never actually starts moving ... the rest of the application works fine (ie database is loaded and results are processed) but the progress bar doesn't ever do anything. Any help someone can provide would be great! Thanks!!

    private void button1_Click(object sender, EventArgs e)
    {
        //START PROGRESS BAR MOVEMENT
        pb.Style = ProgressBarStyle.Marquee;

        LoadDatabase.Groups();

        ProcessResults.GroupOne();

        //END PROGRESS BAR MOVEMENT
        ????
    }
stuartd
  • 70,509
  • 14
  • 132
  • 163
Gazrok
  • 99
  • 2
  • 8
  • 3
    You need to run the job on another thread, eg using a [`BackgroundWorker`](https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx), then the UI thread can update the progress bar while the job is running, – stuartd Oct 13 '15 at 13:58
  • http://stackoverflow.com/questions/312936/windows-forms-progressbar-easiest-way-to-start-stop-marquee or in other words _pb.Visible = false;_ – Steve Oct 13 '15 at 14:04
  • ahhhhhhh thank you Steve! – Gazrok Oct 13 '15 at 14:21

1 Answers1

1

Mark your button1 Click() handler with async, then use await and Task.Run:

    private async void button1_Click(object sender, EventArgs e)
    {
        // START PROGRESS BAR MOVEMENT:
        button1.Enabled = false;
        pb.Style = ProgressBarStyle.Marquee;
        pb.Show();

        // DO THE WORK ON A DIFFERENT THREAD:
        await (Task.Run(() =>
        {
            System.Threading.Thread.Sleep(5000); // simulated work (remove this and uncomment the two lines below)
            //LoadDatabase.Groups();
            //ProcessResults.GroupOne();
        }));

        // END PROGRESS BAR MOVEMENT:
        pb.Hide();
        button1.Enabled = true;
    }
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40