threading question

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

    threading question

    A class in my app starts a new thread, and fires events from within that
    thread.

    The result, if nothing is done to prevent it, is that the events are
    executed in the wrong thread in a form having a member of that class.

    A user class doesn't have an Invoke method: how can I make the worker
    thread invoke the events in the main UI thread that created the class?


    The approach I originally built in does NOT work (I found this out only by
    accident, because a Windows.Forms.T imer I started in one of the the event
    handlers never generated any Tick events.)

    I had added a dummy control to the class:

    Private Shared m_ctl As New Control

    and wrapped all events in functions:

    Private Delegate Sub d_RaiseConnect( )

    Private Sub RaiseConnect()
    If m_ctl.InvokeReq uired Then
    m_ctl.Invoke(Ne w d_RaiseConnect( AddressOf RaiseConnect))
    Else
    RaiseEvent OnConnect()
    End If
    End Sub

    The events are _still_ being fired from the wrong thread: Me.InvokeRequir ed
    is True in the event handler in the form containing the class.

    Upon entry of RaiseConnect in the worker thread, m_ctl.InvokeReq uired is
    False.

    I started thinking later that this is probably correct, as the control
    doesn't have a window, so there's no need to use Invoke to access it, but
    when I make it a TextBox instead of just "Control", it *still* says
    InvokeRequired = False.

    Making it an instance member instead of shared, or instantiating it in the
    class constructor instead of through "as new", makes no difference either.

  • Lucvdv

    #2
    Re: threading question

    On Thu, 02 Sep 2004 10:57:08 +0200, Lucvdv <replace_name@n ull.net> wrote:
    [color=blue]
    > A class in my app starts a new thread, and fires events from within that
    > thread.
    >
    > The result, if nothing is done to prevent it, is that the events are
    > executed in the wrong thread in a form having a member of that class.[/color]

    I found a way out, but it has a side effect: the class can now only be used
    as member of a form, and not in a console application for example.

    If there is a better solution I'd still like to know about it, because the
    class handles communication between applications: there's no real reason
    why it should only be used from within a form (I actually _did_ have test
    and maintenance programs that ran as a console app in a previous version
    of the project).


    My current solution is to pass a reference of the parent form to the
    class's constructor. Instead of a dummy control, it's now using the passed
    form to call Invoke on.


    Declaration of the class in the containing form becomes something like

    Private m_Class As New TestClass(Me)

    And in the class you find:

    Public Sub New(ByRef Parent As Form)
    m_Parent = Parent
    End Sub

    Private Delegate Sub d_FireTest()
    Private Sub FireTest()
    If m_Parent.Invoke Required Then
    m_Parent.Invoke (New d_FireTest(Addr essOf FireTest))
    Else
    RaiseEvent TestEvent()
    End If
    End Sub

    Comment

    • Peter Huang

      #3
      Re: threading question

      Hi,

      Yes, I can reproduce the problem with your code. That is because control's
      handle is not created when you call the InvokeRequired due to the winform's
      optimization. WinForms are not thread-safe and require all calls
      manipulating a control to be made on the control's owning UI thread.
      System.Windows. Forms.Control provides the Invoke and InvokeRequired methods
      to marshal calls onto this thread, but they are only valid if the control's
      native handle already exists. If the control doesn't exist, then
      InvokeRequired will always return false, which can lead to creating the
      native handle on the wrong thread, which can cause data corruption and a
      hung process.

      To make the property work more proper, always make sure to call
      InvokeRequired and Invoke on a control whose handle already exists.
      IsHandleCreated may not be valid when called across threads due to a race
      condition since WinForms may destroy the handle on another thread before
      you have used it. Since you can safely call InvokeRequired on any control
      with a window handle created on the main UI thread, it is safest to call it
      on a known good control rather than on the control which you want to
      manipulate.

      You can create a control which will always keep its window handle by
      creating one specifically for this purpose and maintaining a HandleRef to
      it for the life of your application.

      You may try to make a test by changing your code as below.
      Public Sub New()
      Debug.WriteLine (Thread.Current Thread.Name)
      m_Ctl = New Control
      Dim hwnd As IntPtr = m_Ctl.Handle // force the control's handle
      to be created.
      End Sub


      Best regards,

      Peter Huang
      Microsoft Online Partner Support

      Get Secure! - www.microsoft.com/security
      This posting is provided "AS IS" with no warranties, and confers no rights.

      Comment

      • Lucvdv

        #4
        Re: threading question

        On Mon, 06 Sep 2004 00:48:46 GMT, v-phuang@online.m icrosoft.com ("Peter
        Huang") wrote:
        [color=blue]
        > To make the property work more proper, always make sure to call
        > InvokeRequired and Invoke on a control whose handle already exists.[/color]

        Thanks.
        So it is what I thought at one moment, but scratched from the list - the
        handle didn't exist yet. I thought it wouldn't exist until a child window
        had been created for the control, that it would have to be added to a form
        first (but: see below).
        [color=blue]
        > Dim hwnd As IntPtr = m_Ctl.Handle // force the control's handle
        > to be created.[/color]

        What you put in the comment must have bitten me: I checked the handle's
        numeric value in the debugger once, and got a value that was neither zero
        nor 0xffffffff.
        Just examining it must have caused it to be created.
        I probably didn't let the program continue to the end at that time, or I
        should have seen the difference.


        I just tried it: break the program on "m_Ctl = New Control", expand m_Ctl
        in the Locals pane, and the error doesn't occur.
        Break it, do *not* expand m_Ctl, and the error occurs.

        Comment

        • Peter Huang

          #5
          Re: threading question

          Hi Lucvdv,

          When you attempt to access to the handle, the control's handle will be
          created whether or not it is accessed from debugger or the running code.
          Anyway this is a test, I think an official approach is to to use a control
          on the form whose handle has been created as my last post said.

          Best regards,

          Peter Huang
          Microsoft Online Partner Support

          Get Secure! - www.microsoft.com/security
          This posting is provided "AS IS" with no warranties, and confers no rights.

          Comment

          • lucvdv

            #6
            Re: threading question

            "Peter Huang" wrote:
            [color=blue]
            > Hi Lucvdv,
            >
            > When you attempt to access to the handle, the control's handle will be
            > created whether or not it is accessed from debugger or the running code.
            > Anyway this is a test, I think an official approach is to to use a control
            > on the form whose handle has been created as my last post said.[/color]

            Of course, but it requires the class to know something about the form
            it's going to be used in.

            I solved it like I already said near the start of this thread: the New()
            constructor of the class requires a form to be passed, and it calls
            invoke on that form.


            PS, Peter: are those "Did the response to your question in thread..."
            mails auto-generated? I already considered the thread closed, my last
            message was meant as a comment only ;)

            Comment

            Working...