Question

I am having a minor problem (Just getting back into VB) so sorry for my ignorance/lack of understanding in advance.

My first project is to re-write an IRC Channel Quote/Seen Bot and for it to display crypto currency statistics. anyway back to the question.

I have managed to get the connection working, however when I try and view the data from "GetStream.Read" my Gui freezes, I can understand why this is happening due to the 500ms timer it is in but not how to prevent or overcome it. It just sits waiting for more data to come in.

I was hoping someone would have some ideas or at least point me in the right direction

My code so far

Imports System.Net.Sockets
Imports System.Text

Public Class Form1
Dim vClient As New TcpClient()
Dim vIRCNick = "TESTIRCBOT"
Dim vIRCChannel = "#TESTIRCCHAN"
Dim bytesRead As Integer
Dim buffer(1024) As Byte

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    vClient.Connect("irc.freenode.net", 6667)
    IRCSend("USER " & vIRCNick & " 0 0 :TESTIRCBOT" & vbCrLf)
    IRCSend("NICK " & vIRCNick & vbCrLf)
    IRCSend("JOIN " & vIRCChannel & vbCrLf)

    Timer1.Enabled = True

End Sub

Private Sub IRCSend(vMsg)
    Dim bytes() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(vMsg)
    vClient.GetStream.Write(bytes, 0, bytes.Length)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    IRCSend("PRIVMSG " & vIRCChannel & " :" & TextBox3.Text & vbCrLf)
    TextBox3.Text = ""
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    bytesRead = vClient.GetStream.Read(buffer, 0, buffer.Length)
    If bytesRead > 0 Then
        RichTextBox1.Text = RichTextBox1.Text & (System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, bytesRead))
    End If

End Sub
End Class
Was it helpful?

Solution

You're calling Read, which is a synchronous method. That means that it will block the current thread until data is read. The current thread is the UI thread so the UI freezes.

You need to do the reading on a secondary thread if you want the UI not to freeze. That means either calling Read on a secondary thread or else calling ReadAsync or BeginRead. Any of those options is going to complicate your code but such is the nature of multi-threading.

Also note that, even if you read the data on a secondary thread, you must update the UI on the UI thread only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top