473,663 Members | 2,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Synchronized Collection<T> Recommendation

What is the recommended pattern for implementing a synchronized
(thread-safe) class that inherits from Collection<T>? For example, I want
to implement a SyncRoot property [of type
System.Threadin g.ReaderWriterL ock]. I do see where I can override
(protected) the methods InsertItem, RemoveItem, ClearItems, and SetItem.
However, I do not see an override for GetItem.

Kindest regards,
Michael
Apr 30 '06 #1
28 9123
On Sun, 30 Apr 2006 09:45:40 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:
What is the recommended pattern for implementing a synchronized
(thread-safe) class that inherits from Collection<T>? For example, I want
to implement a SyncRoot property [of type
System.Threadi ng.ReaderWriter Lock]. I do see where I can override
(protected) the methods InsertItem, RemoveItem, ClearItems, and SetItem.
However, I do not see an override for GetItem.

Kindest regards,
Michael


You could inherit from ICollection<T> and write a synced wrapper that
can accept any ICollection<T> and make all the methods syncronized. Then
you can write a standard non synced collection and wrap it in a synced
one?

For one thing you cannot garuntee that at some point some method such as
FastAdd(T[] array) doesn't get added that instead of calling SetItem
calls directly into the underling datastore for speed. Now you have an
unsyncronized method. With a wrapper this wouldn't happen due to the
fact that the FastAdd method would be hidden. If you wanted to use you'd
have to explicitly add access to it and can again ensure it is synced.

Infact Collection<T> is just a wrapper for IList<T> so you could write
an IList<T> wrapper that syncronizes an IList<T> then pass this
syncronized list into Collection<T>:

List<T> baseList = new List<T>();
SyncronizedList <T> syncedList = new SyncronizedList <T>(baseList) ;
Collection<T> col = new Collection<T>(s yncedList);

Unfortunatly they seem to have dropped the IsSyncronized property from
the ICollection<T> interface, so there is no way to tell if a generic
collection is already syncronized so that you only have to wrap it if it
isn't. This is a shame as it means that Collection<T>.I sSyncronized
always returns false even if the inner list is infact syncronized.
Apr 30 '06 #2
Chris. Thanks for your reply. I've read many blogs and articles on "why"
Microsoft didn't--and I quote--"make the same mistake" as they did in .NET
1.1 regarding inclusion of the SyncRoot and IsSynchronized properties in the
..NET 2.0 framework.

IMHO, I disagree with Microsoft's reasoning:
http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do certainly
find use for the SyncRoot and IsSynchronized properties in multi-operation
scenarios (i.e. add one item and remove another in the same protected
operation).

Unless I'm missing something, it seems as though not allowing override of
item retrieval on Collection<T> is an oversight. Granted I could use the
"new" keyword on the Collection<T> indexer but that doesn't seem as elegant.

Again, I appreciate your reply.

- m
"Chris Chilvers" <ke****@dynafus .com> wrote in message
news:ea******** *************** *********@4ax.c om...
On Sun, 30 Apr 2006 09:45:40 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:
What is the recommended pattern for implementing a synchronized
(thread-safe) class that inherits from Collection<T>? For example, I want
to implement a SyncRoot property [of type
System.Thread ing.ReaderWrite rLock]. I do see where I can override
(protected) the methods InsertItem, RemoveItem, ClearItems, and SetItem.
However, I do not see an override for GetItem.

Kindest regards,
Michael


You could inherit from ICollection<T> and write a synced wrapper that
can accept any ICollection<T> and make all the methods syncronized. Then
you can write a standard non synced collection and wrap it in a synced
one?

For one thing you cannot garuntee that at some point some method such as
FastAdd(T[] array) doesn't get added that instead of calling SetItem
calls directly into the underling datastore for speed. Now you have an
unsyncronized method. With a wrapper this wouldn't happen due to the
fact that the FastAdd method would be hidden. If you wanted to use you'd
have to explicitly add access to it and can again ensure it is synced.

Infact Collection<T> is just a wrapper for IList<T> so you could write
an IList<T> wrapper that syncronizes an IList<T> then pass this
syncronized list into Collection<T>:

List<T> baseList = new List<T>();
SyncronizedList <T> syncedList = new SyncronizedList <T>(baseList) ;
Collection<T> col = new Collection<T>(s yncedList);

Unfortunatly they seem to have dropped the IsSyncronized property from
the ICollection<T> interface, so there is no way to tell if a generic
collection is already syncronized so that you only have to wrap it if it
isn't. This is a shame as it means that Collection<T>.I sSyncronized
always returns false even if the inner list is infact syncronized.

Apr 30 '06 #3
| IMHO, I disagree with Microsoft's reasoning:
| http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do certainly
| find use for the SyncRoot and IsSynchronized properties in multi-operation
| scenarios (i.e. add one item and remove another in the same protected
| operation).

I have to agree with MS on this one. To add an item and remove in the same
protected operation means your taking the lock 3 times. Once for the
lock(SyncRoot), and once for each method internally. If you add a .Count in
there, then its four locks. True, you already own the lock, so the other
lock operations are faster, but it is still wasted overhead. As a user of
the collection, it often cleaner, and faster, to just use your own lock and
sync access to the collection yourself. Plus you may need to leverage that
lock for other issues outside of the collection.

--
William Stacey [MVP]

Apr 30 '06 #4
That is true if I were to use lock / Monitor. I prefer to use the
ReaderWriterLoc k class in more cases (especially for the SyncRoot property)
for obvious reasons; I can't know (or presume to know) the usage profile of
the consumer.

I'll still keep my opinion; but then again, you know what those are like ;-)

"William Stacey [MVP]" <wi************ @gmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
| IMHO, I disagree with Microsoft's reasoning:
| http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do
certainly
| find use for the SyncRoot and IsSynchronized properties in
multi-operation
| scenarios (i.e. add one item and remove another in the same protected
| operation).

I have to agree with MS on this one. To add an item and remove in the
same
protected operation means your taking the lock 3 times. Once for the
lock(SyncRoot), and once for each method internally. If you add a .Count
in
there, then its four locks. True, you already own the lock, so the other
lock operations are faster, but it is still wasted overhead. As a user of
the collection, it often cleaner, and faster, to just use your own lock
and
sync access to the collection yourself. Plus you may need to leverage
that
lock for other issues outside of the collection.

--
William Stacey [MVP]

Apr 30 '06 #5
Hit SEND too soon.

That is true if I were to use lock / Monitor. I prefer to use the
ReaderWriterLoc k class in more cases (especially for the SyncRoot property)
for obvious reasons; I can't know (or presume to know) the usage profile of
the consumer.

The purpose of the SyncRoot property IS to leaverage the lock for other
scenarios outside of the collection but as related TO the collection.

I'll still keep my opinion; but then again, you know what those are like ;-)

"William Stacey [MVP]" <wi************ @gmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
| IMHO, I disagree with Microsoft's reasoning:
| http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do
certainly
| find use for the SyncRoot and IsSynchronized properties in
multi-operation
| scenarios (i.e. add one item and remove another in the same protected
| operation).

I have to agree with MS on this one. To add an item and remove in the
same
protected operation means your taking the lock 3 times. Once for the
lock(SyncRoot), and once for each method internally. If you add a .Count
in
there, then its four locks. True, you already own the lock, so the other
lock operations are faster, but it is still wasted overhead. As a user of
the collection, it often cleaner, and faster, to just use your own lock
and
sync access to the collection yourself. Plus you may need to leverage
that
lock for other issues outside of the collection.

--
William Stacey [MVP]

Apr 30 '06 #6
Looking at the reasoning it does make sense to me, if you want something
to be thread safe you shouldn't allow access to (by passing around) an
unsynched version and require that the callee does the appropriate
locking.

Collection<T> is just really a wrapper for IList<T>, seems like it was
only really put in to provide a simple wrapper to make custom
implementations of IList<T> use the old ICollection, IList, and
IEnumerable interface with out having to implement them by hand. Thus it
appears to me that it is not designed to be overrode, and instead the
item that should be overrode or wrapped is the IList being passed into
the Collection<T>.

Might be best just to have two synced wrappers:
SyncedList<T> : IList<T>
SyncedCollectio n<T> : ICollection<T>
On Sun, 30 Apr 2006 10:54:02 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:
Chris. Thanks for your reply. I've read many blogs and articles on "why"
Microsoft didn't--and I quote--"make the same mistake" as they did in .NET
1.1 regarding inclusion of the SyncRoot and IsSynchronized properties in the
.NET 2.0 framework.

IMHO, I disagree with Microsoft's reasoning:
http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do certainly
find use for the SyncRoot and IsSynchronized properties in multi-operation
scenarios (i.e. add one item and remove another in the same protected
operation).

Unless I'm missing something, it seems as though not allowing override of
item retrieval on Collection<T> is an oversight. Granted I could use the
"new" keyword on the Collection<T> indexer but that doesn't seem as elegant.

Again, I appreciate your reply.

- m
"Chris Chilvers" <ke****@dynafus .com> wrote in message
news:ea******* *************** **********@4ax. com...
On Sun, 30 Apr 2006 09:45:40 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:
What is the recommended pattern for implementing a synchronized
(thread-safe) class that inherits from Collection<T>? For example, I want
to implement a SyncRoot property [of type
System.Threa ding.ReaderWrit erLock]. I do see where I can override
(protected ) the methods InsertItem, RemoveItem, ClearItems, and SetItem.
However, I do not see an override for GetItem.

Kindest regards,
Michael


You could inherit from ICollection<T> and write a synced wrapper that
can accept any ICollection<T> and make all the methods syncronized. Then
you can write a standard non synced collection and wrap it in a synced
one?

For one thing you cannot garuntee that at some point some method such as
FastAdd(T[] array) doesn't get added that instead of calling SetItem
calls directly into the underling datastore for speed. Now you have an
unsyncronized method. With a wrapper this wouldn't happen due to the
fact that the FastAdd method would be hidden. If you wanted to use you'd
have to explicitly add access to it and can again ensure it is synced.

Infact Collection<T> is just a wrapper for IList<T> so you could write
an IList<T> wrapper that syncronizes an IList<T> then pass this
syncronized list into Collection<T>:

List<T> baseList = new List<T>();
SyncronizedList <T> syncedList = new SyncronizedList <T>(baseList) ;
Collection<T> col = new Collection<T>(s yncedList);

Unfortunatly they seem to have dropped the IsSyncronized property from
the ICollection<T> interface, so there is no way to tell if a generic
collection is already syncronized so that you only have to wrap it if it
isn't. This is a shame as it means that Collection<T>.I sSyncronized
always returns false even if the inner list is infact syncronized.

Apr 30 '06 #7
Given the current implementations of Collection<T> and List<T>, I agree in
that two synchronized wrappers are the correct approach. I'll proceed along
this path until such time as other possibilities arise.

Again, I do appreciate your time.

"Chris Chilvers" <ke****@dynafus .com> wrote in message
news:te******** *************** *********@4ax.c om...
Looking at the reasoning it does make sense to me, if you want something
to be thread safe you shouldn't allow access to (by passing around) an
unsynched version and require that the callee does the appropriate
locking.

Collection<T> is just really a wrapper for IList<T>, seems like it was
only really put in to provide a simple wrapper to make custom
implementations of IList<T> use the old ICollection, IList, and
IEnumerable interface with out having to implement them by hand. Thus it
appears to me that it is not designed to be overrode, and instead the
item that should be overrode or wrapped is the IList being passed into
the Collection<T>.

Might be best just to have two synced wrappers:
SyncedList<T> : IList<T>
SyncedCollectio n<T> : ICollection<T>
On Sun, 30 Apr 2006 10:54:02 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:
Chris. Thanks for your reply. I've read many blogs and articles on "why"
Microsoft didn't--and I quote--"make the same mistake" as they did in .NET
1.1 regarding inclusion of the SyncRoot and IsSynchronized properties in
the
.NET 2.0 framework.

IMHO, I disagree with Microsoft's reasoning:
http://blogs.msdn.com/brada/archive/.../28/50391.aspx and do certainly
find use for the SyncRoot and IsSynchronized properties in multi-operation
scenarios (i.e. add one item and remove another in the same protected
operation).

Unless I'm missing something, it seems as though not allowing override of
item retrieval on Collection<T> is an oversight. Granted I could use the
"new" keyword on the Collection<T> indexer but that doesn't seem as
elegant.

Again, I appreciate your reply.

- m
"Chris Chilvers" <ke****@dynafus .com> wrote in message
news:ea****** *************** ***********@4ax .com...
On Sun, 30 Apr 2006 09:45:40 -0500, "Michael Primeaux"
<mj********@msn .com> wrote:

What is the recommended pattern for implementing a synchronized
(thread-safe) class that inherits from Collection<T>? For example, I
want
to implement a SyncRoot property [of type
System.Thre ading.ReaderWri terLock]. I do see where I can override
(protecte d) the methods InsertItem, RemoveItem, ClearItems, and SetItem.
However, I do not see an override for GetItem.

Kindest regards,
Michael
You could inherit from ICollection<T> and write a synced wrapper that
can accept any ICollection<T> and make all the methods syncronized. Then
you can write a standard non synced collection and wrap it in a synced
one?

For one thing you cannot garuntee that at some point some method such as
FastAdd(T[] array) doesn't get added that instead of calling SetItem
calls directly into the underling datastore for speed. Now you have an
unsyncronized method. With a wrapper this wouldn't happen due to the
fact that the FastAdd method would be hidden. If you wanted to use you'd
have to explicitly add access to it and can again ensure it is synced.

Infact Collection<T> is just a wrapper for IList<T> so you could write
an IList<T> wrapper that syncronizes an IList<T> then pass this
syncronized list into Collection<T>:

List<T> baseList = new List<T>();
SyncronizedList <T> syncedList = new SyncronizedList <T>(baseList) ;
Collection<T> col = new Collection<T>(s yncedList);

Unfortunatly they seem to have dropped the IsSyncronized property from
the ICollection<T> interface, so there is no way to tell if a generic
collection is already syncronized so that you only have to wrap it if it
isn't. This is a shame as it means that Collection<T>.I sSyncronized
always returns false even if the inner list is infact syncronized.

Apr 30 '06 #8
| That is true if I were to use lock / Monitor. I prefer to use the
| ReaderWriterLoc k class in more cases (especially for the SyncRoot
property)
| for obvious reasons;

Same holds true for ReaderWriteLock . RW may, in fact, not gain you anything
but slower performance. Is your collection doing anything besides updating
a list? If not, then a monitor will most likely be factors faster.

| I can't know (or presume to know) the usage profile of
| the consumer.

Exactly. You can't know, so why implement it? It is a simple matter for
the user to do it as they know what they need.

| I'll still keep my opinion; but then again, you know what those are like
;-)

:)
Apr 30 '06 #9
>> Exactly. You can't know, so why implement it?
The answer is easy; by using lock you presume to know the usage profile of
the consumer is one that doesn't favor a higher read frequency. By using the
ReaderWriterLoc k class, you favor either choice.
Is your collection doing anything besides updating a list? Again, by assuming an answer here you presume to know the usage profile of
the consumer of the collection. In this case, you assume the to know the
consumer favors reads equally as they favor writes. Regardless of whether my
collection only updates a "list", Monitor forces threads to take it in
turns, while the ReaderWriterLoc k only serializes access when writes occur.
A properly written collection (or framework API in general) doesn't assume
to assess the contention model of protected resources. Stated another way;
as the write frequency approaches the read frequency then the use of the
ReadWriterLock versus Monitor becomes moot but ONLY as related to
concurrency rate.

"William Stacey [MVP]" <wi************ @gmail.com> wrote in message
news:ee******** ******@TK2MSFTN GP05.phx.gbl...| That is true if I were to use lock / Monitor. I prefer to use the
| ReaderWriterLoc k class in more cases (especially for the SyncRoot
property)
| for obvious reasons;

Same holds true for ReaderWriteLock . RW may, in fact, not gain you
anything
but slower performance. Is your collection doing anything besides
updating
a list? If not, then a monitor will most likely be factors faster.

| I can't know (or presume to know) the usage profile of
| the consumer.

Exactly. You can't know, so why implement it? It is a simple matter for
the user to do it as they know what they need.

| I'll still keep my opinion; but then again, you know what those are like
;-)

:)

Apr 30 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
10555
by: Donald Firesmith | last post by:
I am having trouble having Google Adsense code stored in XSL converted properly into HTML. The <> unfortunately become &lt; and &gt; and then no longer work. XSL code is: <script type="text/javascript"> <!]> </script> <script type="text/javascript"
5
7588
by: Mike Surcouf | last post by:
Hi All I have a stored procedure wrapper that returns Collection<T>. The wrapper is generated by codesmith so I don't really want to start altering it. I need to use this collection in a datagridview. I would like the ability to add to this collection or delete from this collection using the grid. I know I will need to use Bindinglist<T> for this but I don't seem to be able to cast from
7
57536
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list without itterating through the entire collection and building up a list? 2. is there a common base class, collection or interface that can contain either/both of these collection types and then how do you convert or cast from the base to either a...
5
3837
by: David Longnecker | last post by:
I'm working to create a base framework for our organization for web and client-side applications. The framework interfaces with several of our systems and provides the business and data layer connectivity for basic operations and such. I've ran into a snag that I just can't think myself out of. Here's an example: I have an object for a Student called StudentRecord. It has properties such as name, grade, identification number, etc.
0
8437
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7375
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5660
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4185
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2764
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1759
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.