I have a HashSet that is a collection of client sockets. When a client connects, the socket is added to the HashSet. I then need to access that socket, but I don't know how to access it in the HashSet.
...
clientSockets.Add(listener开发者_如何转开发Socket.EndAccept(async));
WaitForData(lastAddedSocket);
....
How could I determine what lastAddedSocket
is?
There is no way to ask a HashSet "what was the last thing that was added to you?" The order is all jumbled up.
You should simply keep a separate variable called lastAddedSocket
. Every time you add a socket to the HashSet, also assign it to lastAddedSocket
. Then you will be able to look it up easily and in constant time.
It is generally understood that a hashset's order is not guaranteed. While the Java documentation comes right out and says this the closest the MSDN comes is
A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
Information thanks to: Does HashSet preserve insertion order?
That said, it should be fairly easy for you to preserve your last socket yourself.
You will probably want your last to be previous-last when you delete the last one. I recommend using Queue<> in addition to the HashSet so you will be able always remember the sequence in which they arrived, in case that last goes away.
精彩评论