VB.NET multithreading. Calling a call from a user interface control from a class to a separate class file

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

+6
source share
1 answer

The problem is that you are not calling the Msg function on an instance of myForm, but as a generic function of the myForm class.

Change your code in TestClass to add

 Public FormInstance as myForm 

and then replace

 myForm.Msg("Testing Message") 

from

 FormInstance.Msg("Testing Message") 

Then in StartButton_Click add a line

 classEntity.FormInstance = Me 

and you get the expected result.

+3
source

Source: https://habr.com/ru/post/888026/


All Articles