0

I want to have a loading form showing up while the main app connects to db and fetching initial data. Because this can take up 5-10 secs I want to inform the user that something is happening.

This is what I have come up with:

frmStart _frmStart = new frmStart();
Thread t = new Thread(() => _frmStart.ShowDialog());
t.Start();
objDAL = new DBManager();
objDAL.conSTR = Properties.Settings.Default.conDEFAULT;
PrepareForm();
t.Abort();

Is this the best way?

Adam
  • 15,537
  • 2
  • 42
  • 63
e4rthdog
  • 5,103
  • 4
  • 40
  • 89

2 Answers2

2

No, this doesn't solve the frozen UI problem, it merely papers it over. Imperfectly at that, the dialog's parent is the desktop and can easily appear underneath the frozen window and thus not be visible at all. And the dialog isn't modal to the regular windows since it runs on another thread. The failure mode when the user starts clicking on the non-responsive window is very ugly, those clicks all get dispatched when the UI thread comes back alive.

There are workarounds for that (you'd have to pinvoke SetParent and disable the main windows yourself) but that's just solving the wrong problem. You should never let the UI thread block for more than a second. Use a BackgroundWorker to do the heavy lifting, update the form with the query results in the RunWorkerCompleted event handler.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • But if i need just a dialog box with a simple animated gif , and only on application start? The app currently doesn't do the heavy lifting on a separate thread, and although i will change it, i need this solution for now. – e4rthdog Jul 07 '12 at 12:12
1

If you are using WinForms you may want to take a look at this A Pretty Good Splash Screen in C#. If you are using WPF you could take a look at this Implement Splash Screen with WPF.

Alan Bradbury
  • 128
  • 2
  • 8
  • The second link's approach is absolutely appaling. – gwiazdorrr Jul 07 '12 at 10:33
  • You're quite right @gwiazdorr. See this link for a better WPF solution which avoids the static classes and uses a thread: [Creating an Animated Splash Screen In WPF](http://thenullreference.com/blog/the-secrets-of-creating-a-animated-splash-screen-in-wpf/). – Alan Bradbury Jul 07 '12 at 12:11
  • @AlanBradbury: Nice!!! do i need any special instructions on how to mix winforms app with wpf? (having just the splash screen on WPF and the rest in WinForms.... – e4rthdog Jul 07 '12 at 12:16
  • 1
    @e4rthdog you can host WinForms in WPF, but I wouldn't recommend it unless necessary. If you are using WinForms for your application then I would stick with [A Pretty Good Splash Screen in C#](http://www.codeproject.com/Articles/5454/A-Pretty-Good-Splash-Screen-in-C). – Alan Bradbury Jul 07 '12 at 17:32