AsyncCallback method accessing WebBrowser control causes exception

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Artie

    #1

    AsyncCallback method accessing WebBrowser control causes exception

    Hi,

    We have an app which uses an AsyncCallback method to handle the return
    from a COM call.

    In this callback, if we try to do anything with a WebBrowser control,
    we get the following exception:

    "InvalidCastExc eption was unhandled
    Specified cast is not valid"

    If we remove all code which tries to access the WebBrowser, the
    exception doesn't occur.

    Has anyone got any idea why this would happen? We can access any
    other controls in our app and no exception is thrown.

    Any help much appreciated.

    Artie
  • Marc Gravell

    #2
    Re: AsyncCallback method accessing WebBrowser control causesexception

    First-off; have you used Invoke/BeginInvoke to get back to the UI
    thread before touching the controls?

    Otherwise, I'd guess that you simply have a bug - i.e. you are
    genuinely doing an invalid cast, perhaps picking up the wrong element
    from a DHTML query?

    Marc

    Comment

    • Marc Gravell

      #3
      Re: AsyncCallback method accessing WebBrowser control causesexception

      Ah - confusion due to the very confusing Delegate.[Begin]Invoke vs
      Control.[Begin]Invoke; I meant the latter, which pushes work back to
      the UI thread. Your EndInvoke usage sounds like Delegate.EndInv oke...

      What I meant was something like:

      void MyCallback(IAsy ncResult result)
      {
      // (note: this bit runs on a worker thread)
      // TODO: usual stuff to get the answer from result

      // now jump to UI thread before touching controls
      this.Invoke((Me thodInvoker)del egate
      {
      // (note: this bit runs on the UI thread)
      // TODO: things that impact your WebBrowser, e.g.
      webBrowser1.Lef t += 5;
      });
      }

      Comment

      • Marc Gravell

        #4
        Re: AsyncCallback method accessing WebBrowser control causes exception

        I don't pretend that it is an answer to "why", but perhaps one good thing
        about this approach is that it avoids accidental and overly inefficient
        code - i.e.

        x.Foo = 123;
        // ... lots more, perhaps involving a loop
        x.Bar = "abc";

        If each of those lines (executed on a worker thread) silently did an
        Invoke() behind your back, you could get some *seriously* poor performance.
        However, wrap that up a bit (for not much extra work) and it should perform
        OK:

        x.Invoke((Metho dInvoker) {
        x.Foo = 123;
        // ... lots more, perhaps involving a loop
        x.Bar = "abc";
        });

        I suspect that this is more by accident than by intent, however...

        Marc


        Comment

        Working...