我刚刚开始开发Windows Phone 8.1/Windows Store 8.1通用应用程序。我想使用中的SynchronizedCollection<T>
类。NET框架(4.5.1)。但显然,Visual Studio 2013在System.Collections.Generic.SynchronizedCollection
下找不到该类,无论是在我的Windows Phone 8.1还是Windows Store 8.1应用程序项目中。
根据我的项目设置,两者都引用了。NET 4.5.1框架。
他们有办法在这些应用程序中使用SynchronizedCollection<T>
吗?如果没有,是否有其他类别可以用作替代品(包括用于同步处理的锁)?
新系统。集合。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);
}
}
它并不完美,但希望它能帮助你。