Thread safe Events
Hej ...jeg vil gerne lave en class der laver nået i mange Thread og når de har nået at melde vil jeg gerne Raise en Event
men så vil jeg gerne fange denne event i min windows form, så får jeg fejlen
"Cross-thread operation not valid: Control 'RichTextBox1' accessed from a thread other than the thread it was created on."
så kan man lave en invoke og så virker det, men jeg vil gerne løse problemet i min class og ikke i min windows form, kan man lave det ?
/jens
sample kode
--------------
Public Class Form1
Dim WithEvents tester As New ClassTester
Sub tester_event_handler(ByVal _s As String) Handles tester.NewData
Me.RichTextBox1.Text = Me.RichTextBox1.Text & System.Environment.NewLine & _s
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
tester.SimEvent()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
--------------
Public Class ClassTester
Public Shared Event NewData(ByVal _string As String)
Public Sub SimEvent()
Dim i As New Threading.Thread(AddressOf simHandler)
i.Start()
Dim ii As New Threading.Thread(AddressOf simHandler)
ii.Start()
Dim iii As New Threading.Thread(AddressOf simHandler)
iii.Start()
End Sub
Sub simHandler()
Dim b As New Random(System.DateTime.Now.Millisecond)
Dim Sleeptime As Integer = b.Next(1000, 3000)
System.Threading.Thread.Sleep(Sleeptime)
RaiseEvent NewData("Done : " & Sleeptime)
End Sub
End Class
-----