0

I need to create a custom concurrent list of updates. An update can be added to the list or replace an existing one (through an id key). Items can be retrieved from the list by 2 methods: Get the first update or get the first silent update.

I tried to play with existing Concurrent collections but decided to create my own through the use of locking the access to a generic List.

My question is: is there a better way to do this? Take note the list will probably never hold more than a dozen of items and it won't be used intensively so performance is not a problem.

 internal class UpdatesCollection
{
    private List<Update> updatesList;
    private object _lock = new object();

    public UpdatesCollection()
    {
        updatesList = new List<Update>();
    }

    public void InsertOrReplace(Update update)
    {
        lock (_lock)
        {
            var index = updatesList.FindIndex(u => u.PackageId == update.PackageId);
            if (index == -1)
            {
                updatesList.Add(update);
            }
            else {
                updatesList[index] = update;
            }
        }
    }

    public Update First()
    {
        lock (_lock)
        {
            var update = updatesList.FirstOrDefault();
            if (update != null)
            {
                updatesList.RemoveAt(0);
            }

            return update;
        }
    }

    public Update FirstSilent()
    {
        lock (_lock)
        {
            var index = updatesList.FindIndex(u => u.Silent);
            if (index != -1)
            {
                var update = updatesList[index];
                updatesList.RemoveAt(index);
                return update;
            }

            return null;
        }
    }
}
Muaddib
  • 495
  • 5
  • 12

0 Answers0