<p>When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads?</p>

<p>The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread.</p>

<p>Example C# of VB.NET code is appreciated.</p>

[{'answer_id': 62481, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': "<p>I would use a threadpool, this way you won't have to start a new thread every time (since this is kinda expensive). I would also not wait indefinetely for furhter connections, since clients may not close their connections. How do you plan to route the client to the same thread each time?</p>\n\n<p>Sorry, don't have sample.</p>\n"}, {'answer_id': 62547, 'author': 'x0n', 'author_id': 6920, 'author_profile': 'https://Stackoverflow.com/users/6920', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s a great example in the O\'Reilly C# 3.0 Cookbook. You can download the accompanying source from <a href="http://examples.oreilly.com/9780596516109/CSharp3_0CookbookCodeRTM.zip" rel="nofollow noreferrer"><code>http://examples.oreilly.com/9780596516109/CSharp3_0CookbookCodeRTM.zip</code></a></p>\n'}, {'answer_id': 62803, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 2, 'selected': False, 'text': "<p>I believe you do it in the same way as any other asynchronous operation in .NET: you call the BeginXxx version of the method, in this case BeginAcceptSocket. Your callback will execute on the thread pool.</p>\n\n<p>Pooled threads generally scale much better than thread-per-connection: once you get over a few tens of connections, the system works much harder in switching between threads than on getting actual work done. In addition, each thread has its own stack which is typically 1MB in size (though it depends on link flags) which has to be found in the 2GB virtual address space (on 32-bit systems); in practice this limits you to fewer than 1000 threads.</p>\n\n<p>I'm not sure whether .NET's threadpool currently uses it, but Windows has a kernel object called the I/O Completion Port which assists in scalable I/O. You can associate threads with this object, and I/O requests (including accepting incoming connections) can be associated with it. When an I/O completes (e.g. a connection arrives) Windows will release a waiting thread, but only if the number of currently runnable threads (not blocked for some other reason) is less than the configured scalability limit for the completion port. Typically you'd set this to a small multiple of the number of cores.</p>\n"}, {'answer_id': 108766, 'author': 'Dror Helper', 'author_id': 11361, 'author_profile': 'https://Stackoverflow.com/users/11361', 'pm_score': 2, 'selected': False, 'text': "<p>I'd like to suggest a diffrent approach: \nMy suggestion uses only two threads.\n  * one thread checks for incomming connections.\n  * When a new connection opened this info is written to a shared data structure that holds all of the current open connections.\n  * The 2nd thread enumerate that data structure and for each open connection recieve data sent and send replys.</p>\n\n<p>This solution is more scaleable thread-wise and if implemented currectly should have better performance then opening a new thread per opened connection.</p>\n"}, {'answer_id': 247108, 'author': 'Anton', 'author_id': 341413, 'author_profile': 'https://Stackoverflow.com/users/341413', 'pm_score': 5, 'selected': True, 'text': "<p>The code that I've been using looks like this:</p>\n\n<pre><code>class Server\n{\n  private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);\n\n  public void Start()\n  {\n    TcpListener listener = new TcpListener(IPAddress.Any, 5555);\n    listener.Start();\n\n    while(true)\n    {\n      IAsyncResult result =  listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);\n      connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event\n      connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)\n    }\n  }\n\n\n  private void HandleAsyncConnection(IAsyncResult result)\n  {\n    TcpListener listener = (TcpListener)result.AsyncState;\n    TcpClient client = listener.EndAcceptTcpClient(result);\n    connectionWaitHandle.Set(); //Inform the main thread this connection is now handled\n\n    //... Use your TcpClient here\n\n    client.Close();\n  }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/62449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1271/']