0
votes

I just started developing an Windows Phone 8.1 / Windows Store 8.1 universal application. I would like to use the SynchronizedCollection<T> class from the .NET framework (4.5.1). But apparently Visual Studio 2013 doesn't find the class under System.Collections.Generic.SynchronizedCollection, neither in my Windows Phone 8.1, nor Windows Store 8.1 app project.

According to my projects' settings, both reference the .NET 4.5.1 framework for the respective platform.

Is their any way, to use the SynchronizedCollection<T> in these apps? If not, is there any other class, which could be used as a replacement (including locks for synchronisation handling)?

1

1 Answers

2
votes

The new System.Collections.Concurrent (added at .net framework 4) namespace is available for use in a Windows Phone / Store 8.1 app.

Take a look at the documentation here:

Thread-Safe Collections

Based on your comment, I would be tempted to write my own. If your collection won't contain huge numbers of listeners, you could use something like this:

public class ThreadSafeList<T> : IEnumerable<T>
{
    private List<T> _listInternal = new List<T>();
    private object _lockObj = new object();

    public void Add(T newItem)
    {
        lock(_lockObj)
        {
            _listInternal.Add(newItem);
        }
    }

    public bool Remove(T itemToRemove)
    {
        lock (_lockObj)
        {
            return _listInternal.Remove(itemToRemove);
        }
    }


    public IEnumerator<T> GetEnumerator()
    {
        return getCopy().GetEnumerator();                  
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return getCopy().GetEnumerator();
    }

    private List<T> getCopy()
    {
        List<T> copy = new List<T>();
        lock (_lockObj)
        {
            foreach (T item in _listInternal)
                copy.Add(item);
        }
        return copy;
    }
}

Because the implementation of IEnumerable<T> creates a copy of the collection, you can iterate the list using a foreach loop and modify it, something like this:

 ThreadSafeList<String> myStrings = new ThreadSafeList<String>();

 for (int i = 0; i < 10; i++)     
      myStrings.Add(String.Format("String{0}", i));

 foreach (String s in myStrings)
 {
      if (s == "String5")
      {
           // As we are iterating a copy here, there is no guarantee
           // that String5 hasn't been removed by another thread, but 
           // we can still try without causing an exception
           myStrings.Remove(s);
      }
 }

It is by no means perfect, but hopefully it might help you.