Advertisement

02.22.2008 at 11:40AM PST, ID: 23185567
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

Multithreaded Socket class in .Net Framework vb.net or c#

I have a multithreaded socket class i am creating which raises an event when something is received from the appropriate udp port. The class raises the event however i am getting the following error in my form when the event is being raised.

cross-thread operation not valid: control 'ListBox1' accessed from a thread other than the thread it was created on.

Please look over my code below and tell me what i can do to remedy the situation.

Thanks in advance.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
Option Explicit On
Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.Text
Public Class clsListener
    Inherits System.ComponentModel.Component
#Region "Delegates & Events"
    Delegate Sub DataReceived(ByVal Data As Byte())
    Delegate Sub sckErr(ByVal Description As String)
    Public Event DataArrival As DataReceived
    Public Event Sock_Error As sckErr
#End Region
#Region "Private Fields"
    Private RemotePort As Integer = 3520
    Private socketThread As Thread
#End Region
#Region "Methods"
    Public Sub New()
        Try
            socketThread = New Thread(AddressOf ReceiveData)
            socketThread.Start()
        Catch e As Exception
            socketThread.Abort()
        Finally
            socketThread = Nothing
        End Try
 
    End Sub
    Private Sub clsListener_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        Try
            Me.socketThread.Abort()
        Catch ex As Exception
        Finally
            Me.socketThread = Nothing
        End Try
 
    End Sub
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
    Public Sub ReceiveData()
        Do
            Dim localHostEntry As IPHostEntry
            Dim soUdp As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
            Try
                Try
                    localHostEntry = Dns.GetHostEntry(Dns.GetHostName())
                Catch ex As Exception
                    Throw ex
                End Try
                Dim localIpEndPoint As New IPEndPoint(localHostEntry.AddressList(0), RemotePort)
                soUdp.Bind(localIpEndPoint)
                While True
                    Dim received As Byte() = New Byte(255) {}
                    Dim tmpIpEndPoint As New IPEndPoint(localHostEntry.AddressList(0), RemotePort)
                    Dim remoteEP As EndPoint = (tmpIpEndPoint)
                    Dim bytesReceived As Integer = soUdp.ReceiveFrom(received, remoteEP)
                    RaiseEvent DataArrival(received)
                End While
            Catch se As SocketException
                RaiseEvent Sock_Error(se.Message)
            Finally
                soUdp.Close()
            End Try
        Loop
    End Sub
#End Region
End Class
 
 
 
Public Class Form1
    Private WithEvents Tester As New clsListener 
    Private Sub Tester_DataArrival(ByVal Data() As Byte) Handles Tester.DataArrival
        Dim str As String = System.Text.Encoding.ASCII.GetString(Data)
        Me.ListBox1.Items.Add(str)
    End Sub
End Class
Start your free trial to view this solution
Question Stats
Zone: Programming
Question Asked By: talker2004
Solution Provided By: Babycorn-Starfish
Participating Experts: 2
Solution Grade: A
Views: 42
Translate:
Loading Advertisement...
02.22.2008 at 12:00PM PST, ID: 20960857

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.22.2008 at 12:10PM PST, ID: 20960948

Rank: Wizard

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.22.2008 at 12:12PM PST, ID: 20960957

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.22.2008 at 12:33PM PST, ID: 20961132

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
 
Loading Advertisement...
Microsoft
  • Internet Protocols
  • Applications
  • Development
  • OS
  • Hardware
  • Windows Security
Apple
  • Operating Systems
  • Hardware
  • Programming
  • Networking
  • Software
Internet
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Spy / Ad Blockers
  • Web Browsers
  • New Net Users
  • Web Development
  • Chat / IM
  • Anti Spam
  • Web Servers
  • Anti-Virus
  • Email Clients
Gamers
  • Tips
  • Online / MMORPG
  • Puzzle
  • Emulators
  • Action / Adventure
  • Role Playing
  • Consoles
  • Game Programming
  • Strategy
  • Sports
  • Misc
  • Computer Games
Digital Living
  • Hardware
  • Automotive
  • New Net Users
  • New Users
  • Software
  • Digital Music
  • Gaming World
  • Home Security
  • Apple
  • Networking Hardware
Virus & Spyware
  • Vulnerabilities
  • IDS
  • Encryption
  • Anti-Virus
  • Operating Systems Security
  • Software Firewalls
  • WebApplications
  • Cell Phones
  • Operating Systems
  • Internet
  • Hardware Firewalls
Hardware
  • Displays / Monitors
  • Handhelds / PDAs
  • Components
  • Peripherals
  • Laptops/Notebooks
  • Servers
  • Misc
  • Apple
  • Embedded Hardware
  • Networking Hardware
  • Storage
  • Desktops
  • New Users
Software
  • System Utilities
  • Industry Specific
  • Network Management
  • Photos / Graphics
  • Page Layout
  • VMware
  • Misc
  • Web Development
  • OS
  • CYGWIN
  • Voice Recognition
  • Virtualization
  • Message Queue
  • Quality Assurance
  • Security
  • Firewalls
  • MultiMedia Applications
  • Development
  • Database
  • Office / Productivity
  • Business Management
  • OS/2 Apps
  • Server Software
  • Internet / Email
ITPro
  • OS
  • Storage
  • Encryption
  • Operating Systems Security
  • Apple Hardware
  • Laptops & Notebooks
  • Servers
  • Networking Hardware
  • Peripherals
  • Devices
  • Displays / Monitors
  • WebTrends / Stats
  • Search Engines
  • Firewalls
  • Web Computing
  • WebApplications
  • IDS
  • Vulnerabilities
  • Email Clients
  • File Sharing
  • Spy / Ad Blockers
  • Web Browsers
  • Web Servers
  • Networking
  • Anti-Virus
  • Consulting
  • Chat / IM
  • Anti Spam
Developer
  • Web Servers
  • Web Browsers
  • Game Programming
  • Dev Tools
  • Industry Specific
  • Office / Productivity
  • Database
  • CYGWIN
  • Web Development
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Programming
  • Content Management
  • Application Servers
  • Protocols
Storage
  • Removable Backup Media
  • Storage Technology
  • Servers
  • Grid
  • Remote Access
  • Backup / Restore
  • Misc
  • Hard Drives
OS
  • Miscellaneous
  • Security
  • Development
  • Linux
  • VMware
  • MainFrame OS
  • Unix
  • Apple
  • OS / 2
  • AS / 400
  • BeOS
  • Microsoft
  • VMS / OpenVMS
Database
  • Oracle
  • Miscellaneous
  • MySQL
  • Software
  • Sybase
  • Contact Management
  • PostgreSQL
  • Data Manipulation
  • Clarion
  • InterSystems Cache
  • Siebel
  • MUMPS
  • OLAP
  • SQLBase
  • SAS
  • GIS & GPS
  • 4GL
  • Berkeley DB
  • DB2
  • Informix
  • Interbase / Firebird
  • FoxPro
  • Reporting
  • LDAP
  • Filemaker Pro
  • MS SQL Server
  • dBase
  • MS Access
Security
  • Misc
  • Web Browsers
  • Software Firewalls
  • Operating Systems Security
  • File Sharing
  • Spy / Ad Blockers
  • Vulnerabilities
  • WebApplications
  • IDS
  • Anti-Virus
  • Encryption
  • Anti Spam
  • Email Clients
  • VPN
  • Chat / IM
Programming
  • Editors IDEs
  • Installation
  • Handhelds / PDAs
  • Multimedia Programming
  • System / Kernel
  • Automation
  • Algorithms
  • Game
  • Signal Processing
  • Project Management
  • Open Source
  • Database
  • Misc
  • Languages
  • Processor Platforms
  • Theory
Web Development
  • Scripting
  • Blogs
  • Web Servers
  • Software
  • Search Engines
  • Web Graphics
  • Web Services
  • Images
  • Internet Marketing
  • Images and Photos
  • Components
  • Document Imaging
  • Web Languages/Standards
  • Illustration
  • WebApplications
  • Fonts
  • WebTrends / Stats
  • Authoring
  • Digital Camera Software
  • Miscellaneous
Networking
  • Protocols
  • Apple Networking
  • Network Management
  • Message Queue
  • Application Servers
  • Content Management
  • File Servers
  • Email Servers
  • Misc
  • Java Editors & IDEs
  • Wireless
  • Networking Hardware
  • Backup / Restore
  • System Utilities
  • ISPs & Hosting
  • Web Servers
  • Storage Technology
  • Removable Backup Media
  • Servers
  • Web Computing
  • Broadband
  • Grid
  • OS / 2
  • Novell Netware
  • Unix Networking
  • Windows Networking
  • Security
  • Telecommunications
  • Operating Systems
  • Linux Networking
Other
  • Lounge
  • Business Travel
  • Community Support
  • New Net Users
  • Philosophy / Religion
  • Math / Science
  • Miscellaneous
  • URLs
  • Expert Lounge
  • Politics
  • Puzzles / Riddles
  • Automotive
Community Support
  • Suggestions
  • New to EE
  • New Topics
  • CleanUp
  • Announcements
  • General
  • Feedback
  • Input
  • EE Bugs
 
02.22.2008 at 12:00PM PST, ID: 20960857

Rank: Master

you need to create a simple wrapper around your functionality and use a delegate.

 delegate void ListBoxStringAdder(String str);
        private void UpdateListBox(String str)
        {
            if (listBox1.InvokeRequired)
            {
                ListBoxStringAdder lsa = new ListBoxStringAdder(UpdateListBox);
                this.Invoke(lsa, new object[]{str});
            }
            else
            {
                listBox1.Items.Add(str);
            }
        }
Accepted Solution
 
02.22.2008 at 12:10PM PST, ID: 20960948

Rank: Wizard

babycorn has the right answer, but doesn't explain why his answer is required.

Many of the .Net controls are thin wrappers around their win32 equivalents.  The win32 controls are not threadsafe, and therefore the .Net controls are not threadsafe.  When you raise an event on a delegate, the code is run in the thread of the code that raised the event.  This means when you raise the DataArrival event, any method that subscribes to the delegate will be run from your socketThread.  This includes your Tester_DataArrival() event handler.  Since the event handler tries to modify a control from a thread outside the main UI thread, an exception is thrown.  It would be much nicer if you could have code the finds the main thread, and raises your event from that thread, but I don't know how to do that.

Two other points unrelated to your specific question:
1) I'm looking at the constructor for your clsListener class, and I'm not sure it works the way you think it will.
2) The .Net documentation has notes on style that specifically recommend against using hungarian-style prefixes like cls.
Assisted Solution
 
02.22.2008 at 12:12PM PST, ID: 20960957
OK, i am going to try this now.  is there anyway to encapsulate this into the class so that when the event is being raised that you can simply use the listboxes add method?
 
02.22.2008 at 12:33PM PST, ID: 20961132
I am going to split up the points between you both. Thanks alot for your input.

But one thing continues to puzzle me. If you must use the invoke method of the control in order to populate itself than how can the class be used as an interop library for vb6? I was hoping that my dataarrival method would simply pass  the byte array as the event is being raised. We are still using vb6 for alot of things and my vb6 interop libraries have come in hady for use with vb6.
 
 
20080236-EE-VQP-29 / EE_QW_2_20070628