Reputation: 1287
I have a WinForm
called SpalshScreen.cs
with a simple label with the Text
property is set to "Data Loading...". The label is centered in the Form. I also have a public method called DoClose()
method defined.
My MainForm.Form_Load
method contains:
Hide();
SplashScreen form = new SplashScreen();
form.Show();
// Simulate Doing Database Table Load(s)
Thread.Sleep(5000);
form.DoClose();
Show();
However when I run, my Splash does appear but, where the Label Text is suppose to be it only shows a Light Colored Box.
If I change form.Show();
to form.ShowDialog();
the text appears correctly but the main loop pauses until I close the Splash Window.
Upvotes: 1
Views: 635
Reputation: 1287
After a bunch of trial and error... The trick is to Not block the UI Thread as @Servy said.
The Form_Load method needed to change to:
Hide();
Splash.Show();
// Everything after this line must be Non UI Thread Blocking
Task task = new Task(LoadDataAsync);
task.Start();
task.Wait();
Splash.DoClose();
Show();
And I created a LoadDataAsync Method to take care of everything else:
private async void LoadDataAsync()
{
await Context.Employees.LoadAsync();
await Context.Customers.LoadAsync();
// The Invoke/Action Wrapper Keeps Modification of UI Elements from
// complaining about what thread they are on.
if (EmployeeDataGridView.InvokeRequired)
{
Action act = () => EmployeeBindingSource.DataSource = Context.Employees.Local.ToBindingList();
EmployeeDataGridView.Invoke(act);
}
if (CustomerComboBox.InvokeRequired)
{
Action act = () =>
{
CustomerBindingSource.DataSource = GetCustomerList();
CustomerComboBox.SelectedIndex = -1;
};
CustomerComboBox.Invoke(act);
}
}
I also set any of the private fields and private methods I was using to static.
Upvotes: 1
Reputation: 66
Use timer inside your splashscreen form instead of thread.sleep ( for example close splash screen after 5 seconds), and set closed event of it.
var form = new SplashScreen();
form.Closed += (s,e)=>{
Show();
}
form.Show();
Upvotes: 0