Windows Phone 中的 SynchronizedCollection<T> / Store 8.1 应用程序

SynchronizedCollection<T> in Windows Phone / Store 8.1 apps

我刚刚开始开发 Windows Phone 8.1 / Windows Store 8.1 通用应用程序。我想使用 .NET 框架 (4.5.1) 中的 SynchronizedCollection<T> class。但显然 Visual Studio 2013 没有在 System.Collections.Generic.SynchronizedCollection 下找到 class,在我的 Windows Phone 8.1 和 Windows Store 8.1 应用程序项目中都没有.

根据我的项目设置,两者都引用了各自平台的 .NET 4.5.1 框架。

他们有办法在这些应用程序中使用 SynchronizedCollection<T> 吗?如果没有,是否有任何其他 class 可以用作替代品(包括用于同步处理的锁)?

新的 System.Collections.Concurrent(在 .net framework 4 中添加)命名空间可用于 Windows Phone / Store 8.1 应用程序。

查看此处的文档:

Thread-Safe Collections

根据你的评论,我很想写我自己的。如果你的 collection 不会包含大量的听众,你可以使用这样的东西:

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;
    }
}

因为 IEnumerable<T> 的实现创建了 collection 的副本,您可以使用 foreach 循环迭代列表并修改它,如下所示:

 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);
      }
 }

它绝不是完美的,但希望它能对你有所帮助。