Sometimes people don’t even read what they’re typing

Raymond Chen

Raymond

As an even more extreme case of people seeing something, confirming that they see it, but not actually reading it is someone who sees something, types it into an email message, yet still doesn’t read it.

Subject: “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.” exception crashes our program

I’m looking for guidance on why this exception is thrown and how I can avoid it. Here’s a sketch of what we’re doing:

void DoStuff() {                                                              
  try {                
    // attempt operation X, which throws an exception when it fails
  } catch {                
    this.BeginInvoke(new ShowErrorDelegate(this.OnShowError), null);
  }
}

If operation X fails, the catch clause runs, but it throws the exception “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.” Why is it happening? It’s crashing our program. Right now, we’re working around it by wrapping the BeginInvoke inside its own try/catch, but we’d like to understand why the exception is occurring in the first place and how we can avoid it.

Now, I don’t know much about WinForms, so I could be way off base here, but perhaps the problem is that you’re calling BeginInvoke on a control before its window handle has been created. I’m just basing that on the text that you typed into the subject line and again into the message text. The workaround therefore is to make sure the window handle has been created before calling BeginInvoke. (You can imagine any number of ways of ensuring this.)

Though I do admire the approach of “We don’t know what’s going on, so we’ll just wrap it inside an exception handler and pretend it didn’t happen.”

0 comments

Comments are closed. Login to edit/delete your existing comments