I need to generate consecutive sentence of int
values: 0, 1, 2, ...
But I need to access them from different threads.
So I wrote such code:
class Counter
{
private static Counter instance = new Counter();
private static int i = 0;
public static Counter Instance
{
get
{
return instance;
}
}
public int Next()
{
lock (this)
{
return i++;
}
}
public void Reset()
{
lock (this)
{
i = 0;
}
}
}
May this be implemented simpler?
lock
can be avoided somehow, probably c# has built-insynchronized int
or something? – javapowered May 7 at 5:05lock
. – svick May 7 at 9:01