My colleague and I are debating which of these methods to use for auto generating user ID\'s and post ID\'s for identification in the database:
One option uses a single
Your custom method has two problems:
Random
, but doesn't use locking. => Multi threaded access can corrupt its state. After which the output will suck even more than it already does.Random
at the same time(since system startup) they'll probably create the same sequence of random numbers.This means you cannot rely on the output of Random
being unique, no matter how long it is.
I recommend using a CSPRNG (RNGCryptoServiceProvider) even if you don't need security. Its performance is still acceptable for most uses, and I'd trust the quality of its random numbers over Random
. If you you want uniqueness, I recommend getting numbers with around 128 bits.
To generate random strings using RNGCryptoServiceProvider
you can take a look at my answer to How can I generate random 8 character, alphanumeric strings in C#?.
Nowadays GUIDs returned by Guid.NewGuid()
are version 4 GUIDs. They are generated from a PRNG, so they have pretty similar properties to generating a random 122 bit number (the remaining 6 bits are fixed). Its entropy source has much higher quality than what Random
uses, but it's not guaranteed to be cryptographically secure.
But the generation algorithm can change at any time, so you can't rely on that. For example in the past the Windows GUID generation algorithm changed from v1 (based on MAC + timestamp) to v4 (random).