Question on ICollection.SyncRoot implementation
Using "Lutz Roeder's .NET Reflector" on .NET Framwork shows that
collections implement SyncRoot like this:
object ICollection.SyncRoot
{
get
{
if (this._syncRoot == null)
{
Interlocked.CompareExchange(ref this._syncRoot, new object(),
null);
}
return this._syncRoot;
}
}
Now I have to questions on this.
1) (major) Why is it made so? Why not initialize _syncRoot in the
constructor, or even better in declaration like:
private object readonly _syncRoot = new object();
(Note that this also allows the use of readonly.) The construction by
definition is executed only by on thread so no problem. And after the object
is constructed the _syncRoot already exists so you do not have to check for
its existance and do interlocked compare-exchange.
Was optimalization the reason (no object created when no "call" to
SyncRoot)? But on the other hand if you use SyncRoot you must pay for the
null check and interlocked operation. And if one uses a collection of
objects the one more empty object doesn't seem to do much difference. Or am
I wrong here?
2) (minor) Why is this explicite implementation? (The code is extracted from
System.Collections.Generic.LinkedList<T> but it seems to be exactly the same
in every collection.)
Thanks in advance!
Adam Badura
Date:Sat, 18 Aug 2007 18:48:45 +0200
Author:
|