I need to generate a sequence of int
values: { 0, 1, 2, ... }
, but there's a twist: I need to access them from different threads.
So I wrote this 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 in a simpler way?
lock
can be avoided somehow, probably c# has built-insynchronized int
or something? \$\endgroup\$lock
. \$\endgroup\$