I have been trying to figure this out for a few days and am wondering if it is just something simple, I will miss or be completely mistaken.
Example: Two files - TestClass.vb, myForm.vb
TestClass.vb is as follows:
Imports System.Threading Public Class TestClass Private myClassThread As New Thread(AddressOf StartMyClassThread) Public Sub Start() myClassThread.Start() End Sub Private Sub StartMyClassThread() myForm.Msg("Testing Message") End Sub End Class
myForm.vb is a basic form with a control list and a button element called Output and StartButton. The code behind the form is as follows:
Public Class myForm Private classEntity As New TestClass Private Sub StartButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles StartButton.Click Msg("Start Button Pressed") classEntity.Start() End Sub Delegate Sub MsgCallBack(ByVal mesg As String) Public Sub Msg(ByVal mesg As String) If Output.InvokeRequired Then MsgBox("Invoked") Dim d As New MsgCallBack(AddressOf Msg) Invoke(d, New Object() {mesg}) Else MsgBox("Not Invoked") mesg.Trim() Output.Items.Add(mesg) End If End Sub End Class
Result:
Running applications, errors and exceptions. A list and a start button are displayed. I press the start button, and the msgbox says โDoesn't get called,โ as expected, and when I click โOKโ on that msgbox, the โStartโ button is pressed and is added to the List Output control. Immediately after that, msgbox appears again and says "Not Invoked". I expected "Called" as a separate thread is trying to use the List list control. Of course, this leads to an attempt to output Output.Items.Add, which does not lead to the absence of a visible result, since the thread is not allowed to directly update the user interface control.
I must have read small books on different pages, trying to fully understand pit dads and methods, but I feel like I may have fallen into a trap that people can do. With my current understanding and knowledge, I cannot get out of this trap and would appreciate any material or advice.
Respectfully,
Lex