views:

62

answers:

1

What I have?

An object that is saved in a static variable and called whenever needed This object interfaces with another application.

I have two collections (Generic Lists) in this object Logs And "Data That Is PreFeteched" to be used later

Problem is when more than one person is trying to use this object (the object interfaces with another application) modifying the collection leads to exceptions or loss of data

Exception in case of loops or using the Find function of the Generic List

What I am trying to do is removed the prefetched data or logs from time to time. I can do this initially when any function in the object is called, but if the collection is modified when two people (or threads) are trying to call the same function at once leads to exceptions or loss of data

Loss of data in case I go:

        List AlreadySavedData
          {
           get
              {
                 //Rough Syntax maybe incorrect - but in actual application is correct
                _alreadySavedData= _alreadySavedData.Find(Delegate (Data d {return d.CreatedOn.Date == DateTime.Now.Data;}));               

                 return _alreadySavedData;
              }
        }

I thought by doing the above I could at least limit my collection of "data that is pre-fetched" or Logs from day to day. But when trying to access or modify the collection at the same time, sometimes one call to "AlreadySavedData" can overwrite a parallel call which might have just modified(added to) the collection leading to loss of data.

Any help will be appreciated

+4  A: 

If you must have multiple threads using the collection you will need to provide syncronization. The easiest way is to do this:

    protected volatile _alreadySavedData;

    List AlreadySavedData
      {
       get
          {
             lock(_alreadySavedData)
             {
                //Rough Syntax maybe incorrect - but in actual application is correct
               _alreadySavedData= _alreadySavedData.Find(Delegate (Data d {return d.CreatedOn.Date == DateTime.Now.Data;}));               

                return _alreadySavedData;
             }
          }
    }

You will need to do this anywhere the static collection is being altered or used. Dealing with concurrency in multi-threaded applications is problematic at best.

For a complete rant+guide+suggestions on the subject see this article:

csharptest.net