Hello I'm writting an application and I must learn threads,
This is only a test, just for fun, but I had some problems....
I've got two buttons and a textBox on the form, the first button initializes a thread, and the second stop it.
When the thread begins, starts to read a file with a number of bytes, until the end.
But I can't write to the textBox because belongs to another thread!!!
This is only a test, just for fun, but I had some problems....
I've got two buttons and a textBox on the form, the first button initializes a thread, and the second stop it.
When the thread begins, starts to read a file with a number of bytes, until the end.
But I can't write to the textBox because belongs to another thread!!!
Code:
Imports System
Imports System.Threading
Public Class Form1
'Vars
Dim _threadArray(5) As Thread
Dim nThreads As Integer = 0
Dim s As New serverObject
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX1.Click
If (_threadArray(0).IsAlive) Then
MsgBox(_threadArray(0).Name)
_threadArray(0).Abort()
_threadArray(0) = Nothing
End If
End Sub
Private Sub ButtonX2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX2.Click
_threadArray(0) = s.initialize("D:\Prova.txt", Me)
nThreads += 1
End Sub
Public Sub appendText(ByVal str As String)
TextBox1.Text &= str
End Sub
End Class
Public Class serverObject
Dim path As String
Dim fs As IO.FileStream
Dim b(20) As Byte
Dim temp As Text.UTF8Encoding = New Text.UTF8Encoding(True)
Dim frm As Form1
Public Function initialize(ByVal p As String, ByVal f As Form1) As Thread
Dim th As New Thread(AddressOf speakToMe)
path = p
frm = f
fs = IO.File.OpenRead(path)
th.Name = "I'm the server"
th.Start()
Return th
End Function
Private Sub speakToMe()
While (True)
If (fs.CanRead) Then
If fs.Read(b, 0, b.Length) > 0 Then
MsgBox(temp.GetString(b))
'Here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'Here comes the Cross-threading
frm.appendText(temp.GetString(b))
Else
fs.Close()
fs = IO.File.OpenRead(path)
End If
End If
System.Threading.Thread.Sleep(3000)
'MsgBox("I'm alive!!!!!!!!")
End While
End Sub
End Class