我有一個場景,其中多個生產者在網絡中的不同機器上運行。這些是Singleton WCF服務,它將產品(輸出)排隊在Central Store中,這也是Singleton WCF服務。多個生產者,多個消費者和商店問題
有些消費者通過JSON請求調用Central Store來從Central Store出廠產品。產品通過解決某些優先級限制來交付。生產者在1萬分鍾內以非常高的速度生產產品,目的是以同樣的速度向消費者提供服務,而不是讓他們等待。
只要我有3-4個生產者和多達10個消費者,一切正常。但是,當我增加生產者和消費者的一切凍結。
我使用的是TimedLock這是Monitor.TryEnter的包裝。我嘗試了所有類型的同步技術,如ReaderWriterLockSlim和Web上的其他帖子,但結果相同。我避免了ReaderWriterLockSlim,因爲我有大量的寫入而不是讀取。
由於我無法控制消費者和生產者線程,這些線程由WCF產生,因爲他們訪問的是Singleton Store。我無法實施網上提供的產品/消費者樣品。以下是數據存儲的示例代碼。
public class Store:IEnumerable<Product>
{
private List<Product> _Products;
private object _MonitorLock;
public Store()
{
_Products = new List<Product>();
_MonitorLock = new object();
}
public void Add(Product Product)
{
lock (_MonitorLock)
{
_Products.Add(Product);
}
}
public void Remove(Product Product)
{
lock (_MonitorLock)
{
_Products.Remove(Product);
}
}
public int Count
{
get
{
lock (_MonitorLock)
{
return _Products.Count;
}
}
}
public IEnumerator<Product> GetEnumerator()
{
List<Product> ProductsCopy;
lock (_MonitorLock)
{
ProductsCopy = new List<Product>(_Products);
}
foreach (Product oEntry in ProductsCopy)
yield return oEntry;
}
public Product GetHighestPriorityProduct()
{
Product oProduct;
lock (_MonitorLock)
{
//Some Logic to Resolve the Priority
_Products.Remove(oProduct);
}
return oProduct;
}
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
在深入研究問題後,我發現應用程序凍結時僅增加了消費者數量。如果我增加生產者但保持消費者低,它不會凍結。 正如您已經指出的那樣,凍結可能是因爲優先解析需要長時間,並且lock()在整個時間內都會被獲取。 我會嘗試優先隊列併發布反饋。感謝您的建議。 – Protean 2009-09-20 10:50:33