Archive for January 2013

Form.Shown – The Most Useless Event Ever ?

You know how it is. You want to show a form whilst you run a Massively Heroic Background Worker thread to do some work. So you start the thread in the Form.Load event – and when you run it, the form is slow to appear, as are any controls on it.

“I know”, you exclaim in a moment of enlightenment, “why not only start Massively Heroic Background Worker after the form is displayed”.

“Hell, there is even a nice event – Form.Shown – that sounds just the ticket.”

And behold – the form is pretty much just as bad. And if Massively Heroic Background Worker happens to access the CD/DVD drive, which needs to spin up, you may not see your complete form for 5 seconds. (Not sure why after 20+ years of CD/DVD drives in PCs that putting a new disc in a drive still requires your program to hang solid whilst it spins up, but hey ho, thats the cards we are dealt).

So, why has the Shown event not helped ? Probably because it is telling us the form itself is shown. As for its child controls – and perhaps their child controls too – well, “not my problem” says the form.

The solution comes from an unlikely source – the System.Windows.Forms.Application class. It has an Idle event that fires when, well, your application is idle (good lord, no, really) ? This means whilst a cacophony of windows messages are flying about as the various controls on your form are sorting their lives out, your application isn’t idle. But when the noise dies down – your controls have finished doing there initial stuff – you get an Idle event.Now we can launch Massively Heroic Background Worker; sure, if it accesses the CD/DVD drive our app will still temporarily appear to freeze but hey, at least the user can definitely see the entire form which tells them this is going to happen.

So now, in your Form.Load event,

mhbwAnd jobs a good ‘un.

Or is it ? If you have the excellent Resharper installed – and if you don’t then shame on you (or on your boss if they won’t fund it) – you’ll get a warning about access to modified closure on the last line. In this case it is ok, but since I’m calling StartMassivelyHeroicBackgroundWorker(), why not simply do that as an event in the normal way:-

app_idle2

To me that’s a lot tidier.