Whidbey Form Designer crashes with inherited form due to asynchronous events

I am porting some code from 1.1 to 2.0 and ran into this problem. After debugging devenv a bit I was able to get a handle on what's going on.

 

When you have an inherited form in the designer, you should make sure that you do as little as possible in it. That is to say, try to keep the amount of work done in the form to the absolute minimum possible.

This is due to the fact that some code may easily cause crashes in Visual Studio 2005.

 

As an example, create a new Windows Forms application and in Form1, add the following code to the Load event:

 

private void Form1_Load(object sender, EventArgs e)

{

       throw new InvalidOperationException("Smashy smashy!");

}

 

Now add a new Inherited Form to the project called “Form2”. Make sure it inherits from Form1. Save and build your project.

 

Try opening Form2 in the designer – you should see a bunch of errors displayed in the designer – that’s expected behavior.

 

Now, close Form2 and go back to the Form1 designer. Add a ‘Timer’ component to the form. Make sure the Enabled property is true and that the Interval property is set to 5000. Implement the Tick event and add the following code in there:

 

private void timer1_Tick(object sender, EventArgs e)

{

       throw new InvalidOperationException("Smashy smashy!");

}

 

Save and build your project. Now try opening Form2 in the form designer by double clicking it.

 

Kabooooom! Devenv goes bye-bye after 5 seconds.

 

Apparently the form designer can’t handle such exceptions.

To work around the problem, make sure you don’t have any asynchronous events – this includes the BackgroundWorker, Timer, new threads and other things. Probably other things as well are not safe, so just try to do as little as possible.

 

To disable these events, use the DesignMode property – if it’s true, you should avoid any asynchronous events.

 

Free tip: If you have any code in the constructor of your form you may want to move it to Load – the DesignMode property is not yet set in the constructor – it will always be false.