Here We Discuss About Two Threads Associate With Function:-
Here we take:-
1)open window form in with new project in VS.
1)Take two buttons and two level,See in figure:-
Put this code in place of given events:-
Public Class Form3
Public Sub setText()
For i = 0 To 50
Label1.Text = i.ToString
Threading.Thread.Sleep(100)
Next i
End Sub
Public Sub Mysub()
setText()
End Sub
Public Sub Mysub1()
For i = 0 To 50
Label2.Text = i.ToString
Threading.Thread.Sleep(100)
Next i
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Mysub()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Mysub1()
End Sub
Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCall s = False
End Sub
End Class
In this code ,we find at run time :-
a)if you click on button1 ,then you can able to move window and click on button2.
b)you must be wait for completion of execution of buttone1's function.
Then after we add some line of code of thread in our above program:-
Dim MyThread As New System.Threading.Thread( AddressOf Mysub1)
MyThread.Start()
And remove/comment out 'Mysub() then See the complete code with additional code:-
Public Class Form3
Public Sub setText()
For i = 0 To 50
Label1.Text = i.ToString
Threading.Thread.Sleep(100)
Next i
End Sub
Public Sub Mysub()
setText()
End Sub
Public Sub Mysub1()
For i = 0 To 50
Label2.Text = i.ToString
Threading.Thread.Sleep(100)
Next i
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Mysub()
Dim MyThread As New System.Threading.Thread( AddressOf Mysub)
MyThread.Start()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Mysub1()
Dim MyThread As New System.Threading.Thread( AddressOf Mysub1)
MyThread.Start()
End Sub
Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCall s = False
End Sub
End Class
We find both the buttons work parallely and also we can able drag drop window :-
One Important part of this code,we need to check a cross-thread operation,which is occur due to two or more thread run exclusively.for this we write this line in Form3_Load event
CheckForIllegalCrossThreadCall s = False
If we not write this code it generate error shown in figure:-
Conclusion
Multi-threading is necessary for work with multi task operation.
No comments:
Post a Comment