- Код: Выделить всё
Public Class Form1
Inherits Form
Delegate Sub SetTextCallback(ByVal [text] As String)
Private demoThread As Thread = Nothing
Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.Label1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.Label1.Text = text
End If
End Sub
Private Sub ThreadProcSafe()
Dim i As Integer = 0
Do While i < 10
i = i + 1
Me.SetText(i)
Thread.Sleep(100)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.demoThread = New Thread( _
New ThreadStart(AddressOf ThreadProcSafe))
Me.demoThread.Start()
End Sub
End Class
Все отлично работает, но при выполнении той же процедуры но из отдельного класса возникают непонятности: на главной форме Label остается без изменений, IDE никаких ошибок не выдает при этом. В чем причина?
- Код: Выделить всё
Public Class Form1
' Inherits Form
Delegate Sub SetTextCallback(ByVal [text] As String)
Private demoThread As Thread = New Thread( _
New ThreadStart(AddressOf DemoKlass.ThreadProcSave))
'Private WithEvents backgroundWorker1 As BackgroundWorker
Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.Label1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.Label1.Text = text
End If
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.demoThread.Start()
End Sub
Public Class DemoKlass
Public Shared Sub ThreadProcSave()
Dim i As Integer = 0
Do While i < 10
i = i + 1
Form1.SetText(i)
Thread.Sleep(100)
Loop
End Sub
End Class
End Class