Wednesday, May 9, 2007

Problem with generic List class

Hi
I am using a generic list in my program to have a list of objects stored. I want to compare all the objects in this list with object of another class and find all the objects which meet the criteria. To make it more specific I have a class Employee and a class Salary which look like
Employee { Name Salary Age Id}
Salary{ Currency Amount}

Now i am having a List and when now what i want is to get a List of Employees whose salary is greater then 2000. One way to achieve this is to write a method in class Salary which looks like
public bool IsGreaterThen2000(Employee obj)
{ //some logic return true/false;}

and then pass this as predicate to FindAll method however the responsibility of comparison lies with Salary class. I want to shift this responsibility to some other class which already has the logic for comparison. Is there a way to achieve this using existing generic List class in .NET framework.

Any good ideas out there to solve this with .NET framework 2.0 ?????

~Abhishek

Synchronized thread safe Dictionary

While working in a multi threaded environment i tried to work with a dictionary today. After reading some documentation on msdn i understood that the Dictionary class is not really a thread safe class and if we want to do that we need to make it thread safe we need to do it ourselves.
I understood the fact and tried to write a wrapper over this class and make a generic thread safe dictionary for using it in my application.
So what i did in this wrapper is i maintained a reference to the generic dictionary and implemented IDictionary interface. I plainly delegated the calls to the reference however made sure that each of the call acquires the lock over the object and hence i assumed that my dictionary is a thread safe dictionary.
However while discussing it with one of the colleagues i realize that still is not really a thread safe class. It can still cause problem when i am trying to use IEnumerator. Let's see how

when we loop through a dict with 3 elements with SynchronizedDictionary

foreach(KeyValue keyValue in dict) {...}

will perform like

lock

get enumerator

unlock

<--- another thread might modify as dict is not locked now

lock (assuming returned enumerator calls this[TKey key] for fetching items. else it won't be even locked!)

get first item

unlock

<--- another thread might modify as dict is not locked now

lock

get second item

unlock

<--- another thread might modify as dict is not locked now

lock

get third item

unlock


and hence there's a problem.
Any suggestions out there so resolve this problem.

~Abhishek