Threading with server

  • Thread starter Thread starter Advait Mohan Raut
  • Start date Start date
A

Advait Mohan Raut

Hello,
I am writing a server for my own application purpose in C#. For that
I would use TcpListener class 's BeginAcceptSocket method. This will
let me assign separate thread for each connection.
In this scenario I want to include time-out feature i.e. server will
close connection it will be in waiting state for longer time. Now the
problem here is to measure timeout, for each connection do I need to
create one extra thread for each connection ? Or is there any
alternate possible way ?

- Advait
 
Note that this last statement is false.  The BeginAcceptSocket() method 
has nothing to do with whether you assign a separate thread for each  
connection.  You could use AcceptSocket() just as well for that purpose..

BeginAcceptSocket() _does_ allow you to process the connection _requests_ 
asynchronously, but even there you don't get one thread per request.  
There is a pool of threads available for handling i/o completions, and  
they are allocated as needed to process those i/o completions.  The number  
of threads used in the pool is generally much smaller than the number of  
connections, as the threads are shared among all the connections.

Note also that all of this is a _good_ thing.  One thread per connection  
is fairly wasteful, while using the BeginXXX/EndXXX pattern is fairly  
efficient.  So I'm not trying to discourage you from using  
BeginAcceptSocket().  Just trying to make sure you understand what it  
actually does.


Not only is there an alternate way, unless you only have a small number of  
connections to deal with, I would not create one extra thread for each  
connection.  Instead, create a single thread that handles the timeouts for  
all of the connections; make that thread consume an ordered list of  
objects, each containing a DateTime value representing the actual time of 
the timeout and the reference to the associated connection object (e.g.  
Socket).  That thread can use Thread.Sleep() to wait until the next  
DateTime value needed (just subtract the current time from the future time  
to get the elapsed time needed).

Even better, don't bother implementing that logic yourself, but instead  
use a Timer object to handle processing the list of timeouts.

In either case, when a timeout that will happen earlier than any of the  
currently registered timeouts is added, you'll have to reset the  
sleeping/Timer object so that it happens at the appropriate time.

Pete

Hello,
Thank you Peter Duniho for your suggestion. I was a bit confused
with BeginAcceptSocket() . Instead I have replace it with AcceptSocket
() and ASync connecton handler. Also Timer is included
 
Back
Top