[英]SynchronizedCollection<T> in Windows Phone / Store 8.1 apps
I just started developing an Windows Phone 8.1 / Windows Store 8.1 universal application. 我刚刚开始开发Windows Phone 8.1 / Windows Store 8.1通用应用程序。 I would like to use the
SynchronizedCollection<T>
class from the .NET framework (4.5.1). 我想使用.NET框架(4.5.1)中的
SynchronizedCollection<T>
类。 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. 但是显然,Visual Studio 2013在Windows Phone 8.1和Windows Store 8.1应用程序项目中都没有在
System.Collections.Generic.SynchronizedCollection
下找到该类。
According to my projects' settings, both reference the .NET 4.5.1 framework for the respective platform. 根据我的项目的设置,两者均引用各自平台的.NET 4.5.1框架。
Is their any way, to use the SynchronizedCollection<T>
in these apps? 在这些应用程序中使用
SynchronizedCollection<T>
什么办法吗? If not, is there any other class, which could be used as a replacement (including locks for synchronisation handling)? 如果不是,是否还有其他类可以用作替代类(包括用于同步处理的锁)?
The new System.Collections.Concurrent (added at .net framework 4) namespace is available for use in a Windows Phone / Store 8.1 app. 新的System.Collections.Concurrent(在.net framework 4中添加)命名空间可在Windows Phone / Store 8.1应用程序中使用。
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: 因为
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);
}
}
It is by no means perfect, but hopefully it might help you. 它绝不是完美的,但希望它可以对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.