Multi-Threading Problem
Hej eksperter!Jeg får denne fejl:
Illegal cross-thread operation: Control 'txtChat' accessed from a thread other than the thread it was created on.
Her er min frmMain:
Imports System
Imports System.String
Imports System.IO
Imports System.Net.Sockets
Imports System.Threading
Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Hide()
frmConnect.ShowDialog()
Chat.Write("Info", "System", "Main Form Loaded...")
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Chat.Write("Chat", "Me", txtSend.Text)
End Sub
End Class
Class Chat
Public Shared Sub Write(ByVal Type As String, ByVal Sender As String, ByVal ChatText As String)
With frmMain.txtChat
.SelectionStart = Len(.Text)
Select Case Type
Case "Chat"
.SelectionColor = Color.Black
Case "Info"
.SelectionColor = Color.Green
Case "System"
.SelectionColor = Color.Red
End Select
If Not Len(.Text) = 0 Then
.AppendText(vbCrLf)
End If
.AppendText("[22:22]<")
.SelectionStart = Len(.Text)
.SelectionFont = New Font(.Font.Name, .Font.Size, FontStyle.Bold)
.AppendText(Sender)
.SelectionStart = Len(.Text)
.SelectionFont = New Font(.Font.Name, .Font.Size, FontStyle.Regular)
.AppendText("> " & ChatText)
End With
End Sub
End Class
Class ChatClient
Public Sub Main()
Call Chat.Write("System", "System", "Connecting to " & frmConnect.txtIp.Text & ":50000")
Dim client As TcpClient = New TcpClient(frmConnect.txtIp.Text, "50000")
Dim wrt As StreamWriter = New StreamWriter(client.GetStream)
Call (New Thread(AddressOf (New Reader(client)).Run)).Start()
Dim line As String
line = frmMain.txtSend.Text
While Not (line Is Nothing)
wrt.WriteLine("Chat<|||>" + line) '<|||> tagget bruger jeg til at splitte ting med på serveren...
wrt.Flush()
frmMain.txtSend.Text = ""
End While
wrt.WriteLine("Quit")
wrt.Flush()
wrt.Close()
client.Close()
End Sub
End Class
Class Reader
Private rdr As StreamReader
Public Sub New(ByVal cli As TcpClient)
rdr = New StreamReader(cli.GetStream)
End Sub
Public Sub Run()
Try
Dim line As String
line = rdr.ReadLine
While Not (line Is Nothing)
Chat.Write("Chat", "System Tester", line)
line = rdr.ReadLine
End While
Catch e As Exception
' nothing
End Try
End Sub
End Class
Her er min frmConnect:
Imports System.Threading
Public Class frmConnect
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
Me.Hide()
frmMain.Show()
Call (New Thread(AddressOf (New ChatClient()).Main)).Start()
End Sub
End Class
VB.Net 2005 Express markerer 2. og 4. linie her:
Class Chat
Public Shared Sub Write(ByVal Type As String, ByVal Sender As String, ByVal ChatText As String)
With frmMain.txtChat
.SelectionStart = Len(.Text)
Hvad gør jeg galt?
