Question about threads  
Author Message
OldCDude





PostPosted: Visual C# General, Question about threads Top

I created a socket and am asynchronously listening to a TCP port. This calls a method in another thread when a connection comes in, which puts the data into a buffer and sets a boolean variable to true. Is it safe to fill a buffer and set a boolean value from this other thread If so, how can I set an event when a boolean variable is set to true (in the main thread) to alert my code that data is there

Or is there a better way to do this Thanks for any help.



Visual C#11  
 
 
Brendan Grant





PostPosted: Visual C# General, Question about threads Top

From the sounds if it you are working to implement a Producer/Consumer design pattern... the only problem with your implementation from the sounds of it is that it is not thread safe.

Once you've made the operation thread safe so that no two threads can read and write to/from the buffer or the boolean value, then you can look at implementing your own events which will be little different than creating your own event as part of any other class.

The biggest thing to watch out for though is being aware of the threads that are raising/receiving the event and possibly making the actual handling of the event be thread safe as well.

Gotta love the house keeping that good threading takes.



 
 
Mark Dawson





PostPosted: Visual C# General, Question about threads Top

Hi,

as Brendan mentioned this is a good candidate for a producer/consumer scenario, I gave a simple example of how to do this in the following thread: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=1113365&SiteID=1 it might be of use to you.

Mark.



 
 
Brendan Grant





PostPosted: Visual C# General, Question about threads Top

Nice one Mark... that bad boy is getting bookmarked for future questions like that.

 
 
Dreedle





PostPosted: Visual C# General, Question about threads Top

Another option is the Leader/Follower pattern.

Basically it's a thread pool. On start up the first thread from the pool starts to listen on the socket. When it receives it's data it releases another thread from the pool to start listening on the socket and then processes the data itself. When done it returns to the thread pool to wait on it's turn to listen on the socket again.

Or to put it another way, each thread in the pool waits on it's turn to listen on the socket, accepts and performs all processing required on the connection by itself before returning back to the pool to await it's next turn. No need for the listening thread to synchronize with the worker (accepting) thread.

While not suitable for all applications this pattern can work very well session based server applications.