我有一个用例,其中我想从阻塞集合中插入和删除自定义对象(股票)(大图是生产者消费者队列)。
问题陈述与此线程完全相同 -使用 BlockingCollection 更新 ObservableCollection
我不想使用响应式扩展,但想要传统的 C# 方式来执行此逻辑(不幸的是,这是一个硬性要求,并且完全理解其含义)。我的代码片段在这里
MainWindowViewModel.cs
public class MainWindow_VM : ViewModelBase
{
public ObservableCollection<StockModel> stocks { get; set; }
private readonly Dispatcher currentDispatcher;
private BlockingCollection<StockModel> tasks = new BlockingCollection<StockModel>();
#endregion
// All other standard ViewModel logic - Constructor, Command etc
private void handlermethod(object sender, MarketDataEventArgs e)
{
Task.Factory.StartNew(AddUpdateObservableCollection);
// Below thought process (maybe wrong) - How do i add the value to the BlockingCollection through a thread considering I have a ProducerConsumer class standard implementation (which has Enqueue and Dequeue Methods)
using (ProducerConsumerQueue q = new ProducerConsumerQueue())
{
foreach (Stock s in e.updatedstock)
{
StockModel sm = new StockModel();
sm.Symbol = s.Symbol;
sm.Bidprice = s.Bidprice;
q.EnqueueTask(s);
}
}
private void AddUpdateObservableCollection()
{
//Signalling mechanism still missing - when Stock comes into BlockingCollection - then this will start draining.
// Also have to take care of Dispatcher stuff since you can only update ObservableCollection through Dispatcher
foreach (StockModel sm in tasks)
{
if (sm != null)
{
if (stocks.Any(x => x.Symbol == sm.Symbol))
{
var found = stocks.FirstOrDefault(x => x.Symbol == sm.Symbol);
int i = stocks.IndexOf(found);
stocks[i] = sm;
}
else
{
stocks.Add(sm);
}
}
}
}
}