Debugging Gotcha | | Like you are probably aware, .NET raises the Paint Event every time just about anything changes. And many times, it takes a little work to get a desired visual effect to work. Well, beware of what you put and where you put it. First of all, don't ever use any Console.Read or Console.Readline statements in any Event Handlers, in most cases they will block the program from continuing. But a more common one is calling MessageBox.Show. Many folks, particularly those that don't like using Assertions, use MessageBoxes to display information and/or get a program to pause. It's a bad programming technique, but not an uncommon one. Well execute this bit of code:
public static void Main(){
Form frmMain = new Form();
frmMain.Text = "This is an example of what not to do";
frmMain.BackColog = Color.White;
frmMain.Paint = new PaintEventHandler (CustomPaintHandler);
}
|
public static CustomPaintHandler(object sender, PaintEventArgs pea){
MessageBox.Show(this.Text);
}
| This will be one of those mistakes that you don't make twice. If you don't feel like getting stuck in a loop, I'll tip you off on what happens. Something raises the Paint event and the form begins to paint. Then, in the PaintEventHandler we fire a MessageBox.Show. This causes the part of the Form to be covered hence repainted. Then another MessageBox.Show is called. It's the type of infinite loop that would make an CS101 student blush. And unfortunately, most other techniques, even my beloved Debug.Assert wherein the assertion fails will cause the same problem. SO REMEMBER ONE THING! Paint is an event not a method! And you need to be very careful what you include in your event handlers...unless of course you don't mind infinite loops. |