Hello everyone!
I would like to know if it's possible to make the main thread to continue when a secondary thread is finished without using sleep and while cicles to wait for a value.
I tryed activating a handler but the code executed by the handler is executed by the secondary thread and possible errors from cross thread operations can occurr.
For minimize that type of errors and code to prevent, i now have a timer that check those variables for change every 200ms and start the corresponding code but I whant to find a way that do not use CPU for cicles that can be avoided.
I have tryed BackgroundWorkers but the background.runworkercomplete will also give errors of cross thread operations.
Example: I have a sub routine that I want to retrieve some value and have a handler to put in a label that value when the variable are filled.
With a secondary thread or by a backgroundworker, the handler is executed by the secondary thread or by the backgroudworker and allways give me the cross thread error.
I prepared in VB 2010 a simple example of a form with a Textbox and two buttons that allways give me that error. What I want to do is to the textbox be updated by the main thread and not to receive the error.
Example:
Public Class Form1
Private WithEvents aa As New testess
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
aa.str1 = "rthrghfghfg"
End Sub
Private Sub backgroundworkercomplete(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
TextBox1.Text = aa.str1
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim thread As New System.Threading.Thread(AddressOf teste)
thread.IsBackground = True
thread.Start()
End Sub
Private Sub teste()
aa.str1 = "rthrghfghfg"
End Sub
Private Sub testesfim(ByVal val As String) Handles aa.testes
TextBox1.Text = aa.str1
End Sub
End Class
Class testess
Private str As String
Public Event testes(ByVal val As String)
Property str1 As String
Get
str1 = str
End Get
Set(ByVal value As String)
str = value
RaiseEvent testes(str)
End Set
End Property
End Class
Thank you.
Flavio