I have the code:
internal static class IdCounter
{
[ThreadStatic]
private static int _id = 0;
static IdCounter()
{
}
public static int Id
{
get
{
lock(typeof(IdCounter))
{
return _id++;
}
}
}
}
public abstract class Request
{
protected Request(int requestId)
{
RequestId = IdCounter.Id;
}
}
On the second call, i receive RequestId equals 2, not 1, where is the problem? I tried to use Thread.SetData, but result is the same.
Are you checking the value of
IdCounter.Idin the debugger? This will evaluate the property, which will increment it.Modifying operations in property gets are a bad idea.
Also:
Objectto lock on._idisThreadStaticeach thread has its own instance, so there is no need to lock anyway.