How to call public sub of form running in worker thread from main thread

JLSEsq

Newcomer
Joined
Nov 8, 2005
Messages
8
I need help calling a public sub on a form running on a worker thread from the main thread. I think I need to use a delegate, but I've no idea how to declare or call a delegate.

I've created a form with one simple sub...
Visual Basic:
Public Sub Set_Prompt(ByVal Use_Prompt As String)

        Me.Prompt_La.Text = Use_Prompt
End Sub
I create a worker thread which shows the form, and I can close the form from the main thread using this code...

Visual Basic:
Imports System
Imports System.Threading

Module WaitLib

    Dim WaitMsg_Win As WaitMsg = Nothing
    Dim Msg_Thread As Thread
    Dim Thread_Running As Boolean = False
    Dim Use_Msg As String

    Private Sub Show_WaitMsg()

        WaitMsg_Win = New WaitMsg
        WaitMsg_Win.Set_Prompt(Use_Msg)
        WaitMsg_Win.ShowDialog()
        While (True)
            Thread.Sleep(100)
        End While
    End Sub

    Public Sub Display_Wait_Message(ByVal Wait_Msg As String)

        Use_Msg = Wait_Msg

        If (Not Thread_Running) Then
            Try
                Msg_Thread = New Thread(AddressOf Show_WaitMsg)
                Msg_Thread.IsBackground = True
                Msg_Thread.Priority = ThreadPriority.BelowNormal
                Msg_Thread.Name = "WaitMsg Thread"
                Msg_Thread.Start()
                Thread_Running = True
            Catch ex As Exception
            End Try
        Else
            '
            ' Need to call WaitMsg_Win.Set_Prompt(Use_Msg)
            '
        End If
    End Sub

    Public Sub End_Wait_Message()

        If (Thread_Running) Then
            Try
                Msg_Thread.Abort()
                Msg_Thread.Join()
                WaitMsg_Win.Close()
                WaitMsg_Win = Nothing
                Thread_Running = False
            Catch Err_Ex As Exception
                Call Error_Proc(Err_Ex)
            End Try
        End If
    End Sub

End Module
Thanks in advance for all help and suggestions.
 
Last edited by a moderator:
Use Form.Invoke

JLSEsq said:
I need help calling a public sub on a form running on a worker thread from the main thread. I think I need to use a delegate, but I've no idea how to declare or call a delegate.
You will need to use the Invoke method of the Form to run a Sub on the main thread. You can us InvokeRequired to check if you are on the main thread.

Check out the following thread:
http://www.xtremedotnettalk.com/showthread.php?t=95171

It talks about the interaction between a secondary thread and a form.

Todd
 
Back
Top