I was using such code:
class Counter
{
private int i = 0;
public int Next()
{
lock (this)
{
return i++;
}
}
public void Reset()
{
lock (this)
{
i = 0;
}
}
}
I refactored it such a way:
class Counter
{
private int i = 0;
public int Next()
{
return Interlocked.Increment(ref i);
}
public void Reset()
{
i = 0;
}
}
Will that work? I'm using .NET 4.5 if this matters.
Thread.VolatileWrite()(orVolatile.Write()) in yourReset(), but I'm not sure whether it's actually necessary. – svick Aug 28 '12 at 8:52