Asking tutorial for VB.NET Thread
I have a class named TestClass
Public Class TestClass
Private _Count As Integer
Public ReadOnly Property Count() As Integer
Get
For i As Integer = 0 To 999999999
Threading.Thread.Sleep(100)
Next
Return 100
End Get
End Property
End Class
Form the main form, I call the class. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tg As New TestClass
MsgBox(tg.Count)
End Sub
When I call tg.Count
from main form, the main form will become not responding. How to p开发者_运维百科revent my form from not responding. The user can access other menu rather than waiting for the result. Can anyone help me?
Use BackgroundWorker
to run it in a worker thread. That will keep your GUI responding.
http://www.dreamincode.net/forums/topic/88605-the-background-worker/
Drag the BackgroundWorker
componenet from the toolbox onto the form. Now, put your counter loop within the BackgroundWorker_DoWork
event handler, which is autogenerated for you. All you need to do now is to call RunWorkerAsync
on it.
Hope it helps!
Your loop is looping from 0 to 999999999 and delaying 100ms every loop which is halting that current thread. A better solution would be to use a timer, check for your completed condition and restart the timer if necessary. This way, your main form thread will always be responsive.
精彩评论