This happens because you do all the processing in the Load event for the form. This is called before the form is shown for the first time.
While in the event handler, you are preventing the form from actually showing, as the event handler has to complete before anything else can be processed.
What you want to do is use a BackgroundWorker instance to perform your work. This requires you to do the following:
You have some issues here in that you have your Pizza class tightly coupled to the progress bar. This isn't a good idea. Rather, you should have an event that is fired to indicate that the progress has changed, and then call the ProgressChanged event from the event handler for your Pizza instance.
I've moved out the code for your Eat method and encapsulated it in the form to show you an example of how to use the BackgroundWorker class, but the ideal solution would be to expose an event to indicate when the amount of pizza consumed changes.
Also note that you should override the protected Dispose method on the Form class to properly dispose of the BackgroundWorker instance when the form is disposed of.
Here is what the example looks like:
public void SpawnPizzaProgressBarForm(object sender, EventArgs e)
{
FormPizzaProgressBar Form = new FormPizzaProgressBar();
Form.ShowDialog();
}
...
BackgroundWorker worker = new BackgroundWorker();
public void ProgressBarForm_Load(object sender, EventArgs e)
{
// Initialize the background worker.
worker = new BackgroundWorker();
// Indicate that the worker supports progress.
worker.WorkerSupportsProgress = true;
// Subscribe to the DoWork event.
worker.DoWork += (s, e) => {
// Create the pizza instance.
Pizza = new Pizza();
// Process the slices.
foreach (var Slice in Pizza)
{
// Clear the slice.
Slice.Clear();
// Report the progress.
worker.ReportProgress(Slice.Index / Pizza.Count() * 100);
}
};
// Subscribe to the ProgressChanged event.
worker.ProgressChanged = (s, e) => {
// Update the progress bar.
PizzaEatingProgressBar.Value = e.ProgressPercentage;
};
// Subscribe to the RunWorkerCompleted event.
worker.RunWorkerCompleted = (s, e) => {
// Close the dislog.
this.Close();
};
}
// Must override to properly dispose of the background worker.
protected override void Dispose(bool disposing)
{
// Call the base.
base.Disposing(disposing);
// Dispose of the background worker if disposing is true.
if (disposing) worker.Dispose();
}