Basically, it looks like functionally thread-safe, but there is one strategic mistake in your code. You should not use the field buses
as a lock object. The idiomatic technique is this:
public class EventBusManager {
//...
public EventBus GetIncrementUsage(string roomId) {
lock (lockObject) {
//...
return busUsage.Bus;
}
}
public void DecrementUsage(string roomId) {
lock (lockObject) {
//...
}
}
object lockObject = new();
// System.Threading.Lock lockObject = new(); // for .NET 9 and up
}
Note that the field lockObject
should always be private
.
You can find some rationale behind that here. The specifically stated point is that a lock object should be an instance not used for any other purpose.
Thank you.
—SA