I'm in a situation where I have a ASP.NET Web API 2 project hosted on IIS and I'm anticipating concurrency issues. I need to generate random numbers and make sure that they are unique (later stored in the database). To do so, I have implemented a simple in-memory RNG that rely on a static ConcurrentBag. I am aware that this implementation would imply risks on a distributed architecture. Rapidly, the code looks like this :
public interface IRandomNumberGenerator
{
string ReserveNumber();
string ReleaseNumber(string number);
}
public class InMemoryRandomNumberGenerator : IRandomNumberGenerator
{
private static readonly ConcurrentBag<string> Bag = new ConcurrentBag<string>();
public string ReserveNumber()
{
// Add
throw new NotImplementedException();
}
public string ReleaseNumber(string number)
{
// Remove
throw new NotImplementedException();
}
}
This code is intended to be used like so :
var number = rng.ReserveNumber();
StoreIntoDatabase(number);
rng.ReleaseNumber(number);
Am I using the ConcurrentBag
collection appropriately?
Also note that I have simplified my example and that I am not interested in moving code into SQL and use SQL transaction to accomplish this task.