如果您的 StockModel.Quotation 类允许,您可以创建一个池来限制创建的新对象的数量。这是他们有时在游戏中使用的一种技术,以防止垃圾收集器在渲染过程中停止。
这是一个基本的池实现:
class StockQuotationPool
{
private List<StockQuotation> poolItems;
private volatile int itemsInPool;
public StockQuotationPool(int poolSize)
{
this.poolItems = new List<StockQuotation>(poolSize);
this.itemsInPool = poolSize;
}
public StockQuotation Create(string name, decimal value)
{
if (this.itemsInPool == 0)
{
// Block until new item ready - maybe use semaphore.
throw new NotImplementedException();
}
// Items are in the pool, but no items have been created.
if (this.poolItems.Count == 0)
{
this.itemsInPool--;
return new StockQuotation(name, value);
}
// else, return one in the pool
this.itemsInPool--;
var item = this.poolItems[0];
this.poolItems.Remove(item);
item.Name = name;
item.Value = value;
return item;
}
public void Release(StockQuotation quote)
{
if (!this.poolItems.Contains(quote)
{
this.poolItems.Add(quote);
this.itemsInPool++;
}
}
}
假设 StockQuotation 看起来像这样:
class StockQuotation
{
internal StockQuotation(string name, decimal value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public decimal Value { get; set; }
}
然后,您无需调用新的 StockQuotation() 构造函数,而是向池请求一个新实例。池返回一个现有实例(如果需要,您可以预先创建它们)并设置所有属性,使其看起来像一个新实例。您可能需要反复尝试,直到找到足够大的池大小以同时容纳线程。
这是您从线程中调用它的方式。
// Get the pool, maybe from a singleton.
var pool = new StockQuotationPool(100);
var quote = pool.Create("test", 1.00m);
try
{
// Work with quote
}
finally
{
pool.Release(quote);
}
最后,这个类目前不是线程安全的。如果您需要任何帮助,请告诉我。