繁体   English   中英

同步收集 <T> 在Windows Phone / 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>类。 但是显然,Visual Studio 2013在Windows Phone 8.1和Windows Store 8.1应用程序项目中都没有在System.Collections.Generic.SynchronizedCollection下找到该类。

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

在这些应用程序中使用SynchronizedCollection<T>什么办法吗? 如果不是,是否还有其他类可以用作替代类(包括用于同步处理的锁)?

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

在这里查看文档:

线程安全的集合

根据您的评论,我很想写我自己的。 如果您的收藏集中不包含大量的侦听器,则可以使用以下方法:

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>的实现创建了集合的副本,所以您可以使用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);
      }
 }

它绝不是完美的,但希望它可以对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM