8 Replies - 1424 Views - Last Post: 10 July 2012 - 12:56 PM Rate Topic: -----

#1 Jaflem92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 05-July 12

Cross thread error, Sockets, Delegates

Posted 08 July 2012 - 08:26 AM

I am having trouble with cross threading. The problem is in serverloop() and delText(). vb.net is throwing and error that they are not thread safe and i am using a delegate to invoke delText().


Resorces used: http://www.developer...gates-in-vbnet/

Pastebin:
http://pastebin.com/vj1S36f1

Imports System.Net.Sockets
Imports System.Net
Imports System.Xml
Imports System.IO

Public Class frmMain

    Const Title As String = "Test Network XML"

    Dim Myport As Integer = 20000
    Dim count As Integer = 1

    Dim TCPclient As New TcpClient
    Dim TCPListener As TcpListener
    Dim IP As IPAddress

    Public Alive As Boolean = True

    Private Delegate Sub DS(ByVal Name As String, ByVal Test As String)

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        setUp()

        TitleUpdate(count)

        Dim Server As New Threading.Thread(AddressOf ServerLoop)
        Server.Start()
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Alive = False
    End Sub

    ''' <summary>
    ''' Creates a new port number by randow value between 20,000 and 30,000. creates the local listener
    ''' </summary>
    ''' <remarks>For use when form starts up</remarks>
    Private Sub setUp()
        Dim gen As New Random
        Myport = gen.Next(20000, 30000)
        tbxMyPort.Text = Myport

        IP = IPAddress.Parse(tbxHostIP.Text)
        TCPListener = New TcpListener(IP, Myport)
        TCPListener.Start(8)

    End Sub

    ''' <summary>
    ''' Creetes a new thread to handle another window
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        count = count + 1
        Dim T As New System.Threading.Thread(AddressOf Newform)
        T.Start(count)
    End Sub

    ''' <summary>
    ''' Creates a new window and performs a loop as long as the window is "alive"
    ''' </summary>
    ''' <param name="xCount">The current number of windows created</param>
    ''' <remarks>For use by a new thread</remarks>
    Private Sub Newform(ByVal xCount As Integer)
        Dim frmNew As New frmMain

        frmNew.Show()
        frmNew.TitleUpdate(xCount)
        While frmNew.Alive
            Application.DoEvents()
        End While
    End Sub

    ''' <summary>
    ''' Updates the title in the form's window
    ''' </summary>
    ''' <param name="xcount">The current number of windows created</param>
    ''' <remarks></remarks>
    Public Sub TitleUpdate(ByVal xcount As Integer)
        count = xcount
        Me.Text = Title & " - " & count
    End Sub

    ''' <summary>
    ''' Loops while form is "Alive". Accepts incoming sockets and has the dataset dsNetwork read stream. Then reads last row sent and displays it to tbxDisplay with a delegate.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ServerLoop()

        While Me.Alive
            Try
                Dim tcpclient As New TcpClient

                tcpclient = TCPListener.AcceptTcpClient()

                Dim netstream As NetworkStream = tcpclient.GetStream()

                dsNetwork.ReadXml(netstream)

                netstream.Close()
                tcpclient.Close()
            Catch ex As Exception
                MessageBox.Show(ex.Message.ToString & vbCrLf & ex.InnerException.ToString, "Error")
            End Try

            Dim name As String
            Dim text As String

            Dim cRows As Integer = dsNetwork.Tables("Network").Rows.Count - 1

            name = dsNetwork.Tables("Network").Rows(cRows).Item("Name")
            text = dsNetwork.Tables("Network").Rows(cRows).Item("Text")

            Dim del As DS
            del = New DS(AddressOf DelText)
            del.Invoke(name, text)



        End While

    End Sub

    ''' <summary>
    ''' Delegate sub. Perpose format and display passed values
    ''' </summary>
    ''' <param name="Name"></param>
    ''' <param name="Text"></param>
    ''' <remarks>To be called by delegate only</remarks>
    Private Sub DelText(ByVal Name As String, ByVal Text As String)
        tbxDisplay.Text = String.Format("Name: {0}" & vbCrLf & "Text: {1}", Name, Text) 'is not thread safe
    End Sub

    ''' <summary>
    ''' Reads info from both name and text Textboxs and puts them into a dataset dsNetwork. Sends the data over TCP socket using xml.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

        Dim Row As DataRow = dsNetwork.Tables("Network").NewRow()

        Row("Name") = tbxName
        Row("Text") = tbxText
        dsNetwork.Tables("Network").Rows.Add(Row)
        Try
            TCPclient.Connect(IP, CInt(tbxPort.Text))

            Dim netstream As NetworkStream = TCPclient.GetStream()

            dsNetwork.WriteXml(netstream)
            dsNetwork.Tables("Network").Clear()

            netstream.Flush()
            netstream.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString & vbCrLf & ex.InnerException.ToString, "Error")
        Finally
            TCPclient.Close()
        End Try


    End Sub
End Class



Is This A Good Question/Topic? 0
  • +

Replies To: Cross thread error, Sockets, Delegates

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5674
  • View blog
  • Posts: 12,186
  • Joined: 02-June 10

Re: Cross thread error, Sockets, Delegates

Posted 08 July 2012 - 09:30 AM

Trying to directly affect GUI elements across thread barriers, via invoke or not, is just bad coding practice.

Instead have one class raise an event with parameters, and have the class responsible for doing the delete subscribe to that event.

This is considered proper separation of responsibilities. The server thread is responsible for communication. The GUI is responsible for the GUI. Don't make the server class responsible for the GUI. That makes it 'tightly bound' and is strongly frowned upon. It makes the server something that you can't easily pick up and re-use in another application or form because it is bound to this one. But if it just raises an event that says delete(deleteArguments blahblah) it breaks that dependancy. The server class can be re-used without having to scrub through hundreds of lines of code.


[*]Q:...do multi-threading? Having a problem with cross-threading...

Was This Post Helpful? 0
  • +
  • -

#3 Jaflem92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 05-July 12

Re: Cross thread error, Sockets, Delegates

Posted 08 July 2012 - 11:52 AM

thank you but i can not understand most of those links because they all all in C#, i do not know that language.
Was This Post Helpful? 0
  • +
  • -

#4 _HAWK_  Icon User is offline

  • Master(Of Foo)
  • member icon

Reputation: 1064
  • View blog
  • Posts: 4,167
  • Joined: 02-July 08

Re: Cross thread error, Sockets, Delegates

Posted 08 July 2012 - 12:36 PM

Raising events from other threads still requires delegates.
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5674
  • View blog
  • Posts: 12,186
  • Joined: 02-June 10

Re: Cross thread error, Sockets, Delegates

Posted 08 July 2012 - 12:39 PM

What do you mean by "from other threads" ?
Are you suggesting that thread/class A should try to raise an event that exists on thread/class B?
Was This Post Helpful? 0
  • +
  • -

#6 Jaflem92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 05-July 12

Re: Cross thread error, Sockets, Delegates

Posted 10 July 2012 - 04:52 AM

can anyone help inform me what is wrong with my delegate.
Was This Post Helpful? 0
  • +
  • -

#7 m_wylie85  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 96
  • View blog
  • Posts: 899
  • Joined: 15-October 10

Re: Cross thread error, Sockets, Delegates

Posted 10 July 2012 - 05:32 AM

Hey have a look at below this may help you:

    Private Delegate Sub rtbCityPSDel1(ByVal myString As String)

    Private Sub subRtbPSCity1(ByVal myString As String)
        rtbPS.Text = myString
    End Sub

 Public sub BinaryFileSearchCity()
                If RichTextBox1.InvokeRequired Then
                    RichTextBox1.Invoke(New rtbCityPSDel1(AddressOf subRtbPSCity1), yourString)
                Else
                    RichTextBox1.Text &= yourString       
         End If 
End Sub


However like tlhIn`toq said this is not the right way to do this but this may help you do what you want. If i was you i would look into background workers they are easier to use.


    Private Sub btnOpenCityMerges_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenCityMerges.Click
        Dim thread As New System.Threading.Thread(AddressOf BinaryFileSearchCity)
        thread.Start()
    End Sub

This post has been edited by m_wylie85: 10 July 2012 - 05:34 AM

Was This Post Helpful? 0
  • +
  • -

#8 Jaflem92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 05-July 12

Re: Cross thread error, Sockets, Delegates

Posted 10 July 2012 - 12:14 PM

Question about events: Can threadA raise an event that effects the GUI on threadB safely? For example if the server got the data and raised an event that passed the string and the event handler modified the GUI would that work with out a delegate?
Was This Post Helpful? 0
  • +
  • -

#9 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2271
  • View blog
  • Posts: 9,498
  • Joined: 29-May 08

Re: Cross thread error, Sockets, Delegates

Posted 10 July 2012 - 12:56 PM

Is there any reason stop you creating a quick and simple project to test it out, and see?
It ain't going to take that long.

Instead of looking for ways to circumvent the system, work with it. As it help you code better.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1