Problem
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?
Solution
private static int i = 0;
Are you sure that i
should be static? If it’s static there isn’t too much sense of the Counter instance = new Counter()
instance and the Next
and the Reset
methods also could be static.
Anyway, I’d use a longer variable name, like nextValue
for better readability.
Furthermore, consider the drawbacks of the Singleton pattern:
This pattern makes unit testing far more difficult,
as it introduces global state into an application.
More on Wikipedia.
Never lock on this
as your callers can also do the same and cause deadlocks where you don’t expect them. See below where I create and use a private
locking variable. And made i
an instance variable since you use a singleton instance anyhow.
class Counter
{
private static readonly Counter instance = new Counter();
private static readonly object locker = new object();
private int i;
public static Counter Instance
{
get
{
return instance;
}
}
public int Next()
{
lock (locker)
{
return i++;
}
}
public void Reset()
{
lock (locker)
{
i = 0;
}
}
}