Rolandpish wrote:
Hi there.
I'm doing an application in C# 2005.
I was used in VB6 to put code in Forms load event in order to initialize
some values of the controls (grid values, text boxes values, label captions,
among others). Sometimes that code includes retrieving information from a
database.
Now that I'm doing this in C# 2005, I realized that I can put that code
either in Form load event or in the constructor of the form after the
InitializeComponent(). I have tested both and they work exactly the same
(same results without runtime errors). So, at this point I think I need some
technical advise on why one is better than the other and which one is
recommended whereas the code I put in includes retrieving info from a
database.
Generally speaking, your constructor should run as quickly as possible
and return a constructed object to the caller as quickly as possible.
Certainly you don't want to start background threads and wait on them
in a constructor.
And that's how you should do database calls in a WinForms application:
you should do it on a background thread. Many of my Load events are
split into three methods: OnLoad(), which runs on the UI thread, sets
up bindings for my control and does other setup, disables the entire
form (so the user can't mess with it), then launches BackgroundLoad(),
which runs on a background thread and does the database fetches.
BackgroundLoad() then invokes FinishLoad() on the UI thread again to
re-enable the form now that the loading is complete.
The net effect is that while the application is fetching from the
database the window is still responsive: you can drag it and minimize
it. If I were to do the database fetch without a background thread then
the UI would completely "freeze" until the database call was complete,
which is not nice WinForms etiquette.
So... do the minimum you have to in the constructor, and do the heavy
lifting in OnLoad. Even if you don't bother doing proper threading, at
least you're set up to do it later.