4 ms·
I'm not sure if it would be allowed to hoist `dataQueue.Count` out of the loop. The docs [0] say that multiple concurrent readers are supported, so I'm not sure
by Measter 6y ago
I'm not sure if it would be allowed to hoist `dataQueue.Count` out of the loop. The docs [0] say that multiple concurrent readers are supported, so I'm not sure if the compiler would be allowed to assume anything about the call's return value.
You are correct in that `Count` is a property, and it could be doing extra things, but according to the implementation [1] it just returns the value of a private integer. Of course, this is an implementation detail and shouldn't be relied upon, but I'm not sure how much that could be changed.
However, you are mistaken about the code continuing to work if `dataQueue.Count` were replaced with an RNG, or if it were otherwise higher than it should be. The `Dequeue` function raises an exception if called on an empty queue. This one is part of the API, not an implementation detail. An uncaught exception here would crash the thread, not just blindly carry on.
Of course, I'm no expert, and could just be talking out of my ass.
[0] https://docs.microsoft.com/en-gb/dotnet/api/system.collections.generic.queue-1?view=netcore-3.1#thread-safety https://docs.microsoft.com/en-gb/dotnet/api/system.collectio...
[1] https://github.com/dotnet/runtime/blob/master/src/libraries/System.Collections/src/System/Collections/Generic/Queue.cs https://github.com/dotnet/runtime/blob/master/src/libraries/...
- gpderetta 6y agoConcurrent readers are supported, but not concurrent writers and readers. As Count is getting called outside of the critical section, the compiler can assume that there are no concurrent writers. Admittedly, the following critical section would make it hard for the compiler to actually apply any optimization in practice. Count is implemented as a simple read currently, but that's not guaranteed to be the case in the future (that's the whole reason for having a property. Fair enough about the rng, I'm not really a c# programmer, so I just assumed that dequeue would return a null on an empty queue. I'm not an expert either, and certainly not a c# expert (although I kind of like the language, I haven't written a line in 7 years), so YMMV.