We had a need to generate unique ids for connections in our db. We used the following code:
public class NotificationsClientConnection : IDisposable { private static int _counter = 0; private readonly WebSocket _webSocket; private readonly DocumentDatabase _documentDatabase; private readonly DateTime _startedAt; public NotificationsClientConnection(WebSocket webSocket, DocumentDatabase documentDatabase) { _webSocket = webSocket; _documentDatabase = documentDatabase; _startedAt = SystemTime.UtcNow; } public int Id => Interlocked.Increment(ref _counter); public TimeSpan Age => SystemTime.UtcNow - _startedAt; }
Do you see the bug? It is a subtle one.
When you are ready, peek below.
.
.
.
.
.
.
.
.
.
.
.
.
.
The issue is in the following line:
public int Id => Interlocked.Increment(ref _counter);
The intent was to create a field that would be initialized on startup. Unfortunately, the usage of the lambda symbol "=>" instead of assignment "=" turned that into a computed property, which will return a new value on every call.