Today I got here nice answer that will resolve my problem. Unfortunately, I forgot to ask how about locking.
The issue was simple – in the server, each connected client will get an unique ID (reusable) from 1 to 500, which is maximum of clients.
The answer was to create a qeue and use waiting elements for new connections and just return them back when they are released.
I’m not sure whether I understand correctly – also I should init the qeue with 500 elements (ints) and just take them one by one and return back once released?
If so, what about locking here? My question was mainly aimed on performance because I was using lock.
If you can use Parallel Extensions go for a ConcurrentQueue
If you can’t you can find how to implement your own in this article by Herb Sutter
By the way, the Jon Skeet answer is telling you to just try to unqueue and if empty generate and use. When you’re done with an id, simply return it by enqueuing it. There’s no reference to 500 ids. IF you need to limit to 500 ids then you will need to initialize the queue with your 500 ids and then, instead of generating new ones, BLOCK when the queue is empty. For that a consumer/producer pattern will be better suited.