Reputation: 1617
I'm maintaining an older winforms application where the first window takes 3-5 seconds to load due to database queries, datagrid customization and loading lots of data in.
I'm supposed to add a front screen to this where the user can choose between this old window and new functionality which is yet to be implemented.
So, in addition to refactoring some of the db queries and other older code, I want to improve the loading time of this window by doing this:
This is what I have:
private void startBackgroundLoading()
{
var myThread = new Thread(openSlowLoadingWindow);
myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();
}
private void openSlowLoadingWindow()
{
System.Windowns.Forms.Application.Run(new SlowWindow());
}
I'm using Application.Run() because the two windows (front-screen and slow-loading) illustrated above are in separate projects.
Obviously the code above will start the new thread and show me the window when its done loading, but as explained above, I would like to tell it when to actually show itself.
I've tried several ways to run the new thread in the background, hide the window and various other things.
I'm relatively new to programming, so if I'm attacking this from the completely wrong angle, please let me know how I can improve.
I'm bound to .net 4.0 so the new async/await stuff is not an option.
Best regards, Eric
Upvotes: 2
Views: 3946
Reputation: 1116
have you tried creating (but not running) the slow loading window in your parallel thread and then simply showing this window when it is needed?
This will work in the scenario where the database calls and slow aspects of displaying the window are in the constructor of the window.
Upvotes: 1
Reputation: 4868
You can try to add this event handler to the slow form:
private void SlowWindow_Shown(object sender, EventArgs e)
{
Hide();
}
And add this method to call from the front screen:
public void ShowCrossThread()
{
this.Invoke(new Action(() => { Show(); }));
}
Then in the front screen you need to do the following:
SlowForm _slowForm;
private void openSlowLoadingWindow()
{
_slowForm = new SlowForm();
System.Windows.Forms.Application.Run(_slowForm);
}
private void btnSlowForm_Click(object sender, EventArgs e)
{
_slowForm.ShowFromThread();
Hide();
}
Upvotes: 0