簡體   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