views:

880

answers:

1

I have some forms that takes a bit of time to open because they currently get some stuff from a database in their Load event handler.

Is it possible to somehow load the forms in a separate thread and show them to the user when that is done?

If loading them so that the Load event handler is fired is not possible, maybe having a IPreloadable interface might do the trick with a Preload method, and then move the slow loading contents into that. If it is possible to show the form from a separate thread that is... guess I would need to use Invoke or something similar?

+2  A: 

If you load different forms on different threads, you'll have to be very careful when you make calls between the forms - you'll need to use Control.Invoke/BeginInvoke all over the place.

Note that while each top level window can run on a different thread, all the controls within a window must be created (or rather, they must have their handle created) on the thread for that window.

Why not load the database information in the background, and then when that's finished then you can build the actual form and display it? (Until then you might either want to change to a wait cursor, or possibly put a "Loading data..." status message somewhere.

Jon Skeet
Would of course have to have a status message and maybe a status bar set to marquee or something somewhere while this was happening. But how would you load the database information in the background and then build the actual form? Like, where do you do it? In the constructor instead of the load event handler? Or not in the form at all, but in the parent form or something?
Svish
Do it using BackgroundWorker, and then have the RunWorkerCompleted event handler use the data that's just been fetched.
Jon Skeet
So, Show Form with empty controls -> fetch data with BackgroundWorker -> Create missing/populate controls; or fetch data with BackGroundWorker -> Show form and populate controls?
Svish
Yup. Personally I'd go with the latter, probably.
Jon Skeet
Fantastic. Will have to try one of those then =)
Svish