|
VB.NET - Cross-thread operation not valid.
When your Create an Vb.net application, it runs in its own Default Threat. so say if you have a large loop, most likely your application will HANG. you can avoid this by creating a secod Thread... and you Loop in second thread.
Here is the Code....
Imports System.Threading
Public Class Form1
Private Delegate Sub myDel(ByVal i As Integer)
Dim t As Thread
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
t = New Thread(AddressOf myCounter)
t.Name = "ElizaKhan"
t.Start()
End Sub
Private Sub myCounter()
For i As Integer = 0 To 1000000000
ok(i)
Next
End Sub
Private Sub ok(ByVal i As Integer)
If Me.InvokeRequired Then
Dim jk As New myDel(AddressOf ok)
Me.Invoke(jk, i)
Else
lbl1.Text = i
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
t.Abort()
End Sub
End Class
So Why did I created method ok()? this is because our thread is excuting a method/sub, which is trying to Access a Label Control, which actually exists on Parent UI (hence on default Thread).
Workaround was to Create a Delegate and the Invoke it using Invoke method, this will put the method back on Parent Thread.
Good Luck
Cross-thread operation not valid
|