Reputation: 7355
There is a TCP server project I'm working on. It asynchronously listens the specified port for connections, accepts new connections and begins to wait for data from them. Each new client sends its ID when it connects, this way I know which socket belongs to which client.
Minimum of 100000 clients are going to be connected to the server at the same time.
The question is how should I store these clients?
class Client
{
public Socket Socket { get; set; }
public int ID { get; set; }
}
Something like List<Client>
would definitely break since List<T>
is not a thread-safe type. I should add the client to the list when it connects to the server, remove it from the list when the connection is lost. I also need to be able to send a message to the client with the ID of 5, for example and iterating a List<T>
in an asynchronous environment is a terrible idea. I think locking a sync root every time that I need to interact with the collection wouldn't do any good when it comes to performance.
So, what should I use for performance?
Edit: I use .NET 4
Upvotes: 0
Views: 344
Reputation: 2601
Instead of List<Client>
you should use Dictionary<int, Client>
. By this you can access client of any id with single line of code e.g.
Dictionary<int, Client> connected = new Dictionary<int, Client>();
Client cc = connected[5];
byte[] data = new byte[100]; // any data here
cc.SendData(data);
Upvotes: 0
Reputation: 522
I would use a thread-safe dictionary with the ID as the key. If you're using .net 4 you can use the System.Collections.Concurrent.ConcurrentDictionary - if not you can either roll your own or check out this url for a nice one that uses reader/writer locks
http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx
Upvotes: 3