Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progressbar for long running function WP7 C#

I am writing a sudoku solver app. The calculation time of the solver in certain cases can exceed 3 seconds, which would require a progress bar.

so my code:

private void solveButton_Click(object sender, RoutedEventArgs e)
{
    progressBar1.Visibility = Visibility.Visible;
    progressBar1.IsIndeterminate = true;
    mySolver.Solve(initialValue)
    progressBar1.Visilibity=Visilibity.collapsed;
    progressBar1.IsIndeterminate = false;
}

The code here is a condensed version of my actual code. This code doesn't work, as the progress bar does not appear at all. It seems to me that the UI updates only after event is finised executed. If I didn't hide the progressbar after the solver step, the progressBar appears after the sudoku is solved. Replacing the solver with thread.sleep(1000) also results in the same UI update.

thanks for your help.

like image 237
Alvin Avatar asked Dec 21 '22 09:12

Alvin


2 Answers

You should start the solver on a separate thread. That way the user interface thread can keep working on user interface objects even during the solving process, which allows your progress bar to be drawn on the screen and updated.

like image 134
Phil Avatar answered Dec 27 '22 12:12

Phil


Problem is that your UI thread is not getting free in between to display the progress bar You need to use the background worker to solve the problem and in the main UI thread you should display the progress bar

  private void solveButton_Click(object sender, RoutedEventArgs e)
    {
       BackgroundWorker bg = new BackgroundWorker();
       bg.DoWork += new DoWorkEventHandler(DoWork);
       bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
       bg.RunWorkerAsync(); 

       progressBar1.Visibility = Visibility.Visible;
       progressBar1.IsIndeterminate = true;         
    }

void DoWork(Object sender, DoWorkEventArgs args)
{
     mySolver.Solve(initialValue)
}

void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
{

    //  this method will be called once background worker has completed it's task
      progressBar1.Visilibity=Visilibity.collapsed;
      progressBar1.IsIndeterminate = false
}
like image 39
Haris Hasan Avatar answered Dec 27 '22 11:12

Haris Hasan