How thread safety and random generation work in Nanoid
masterNanoid uses a cryptographically strong random generator by default.
Default Behavior
It uses an internal [ThreadStatic] wrapper over System.Security.Cryptography.RandomNumberGenerator. This creates a separate instance of the generator per thread, ensuring thread safety without the performance overhead of locks.
Custom Random Generators
You can provide your own random generator (e.g., System.Random) to Nanoid.Generate. This is useful for seed-based generation.
Warning: If you provide a global random generator, you are responsible for managing its thread safety.
Preloading the Global Generator
The global random generator is lazily initialized. To force initialization on the current thread immediately, access the Nanoid.GlobalRandom getter.
// Using a seed-based System.Random generator
var random = new Random(10);
var id = Nanoid.Generate(random, Nanoid.Alphabets.Letters, 10); //=> "fbAeFaaDeb"