全部 -
我目前有一个端到端工作的 POC WPF 项目。该应用程序模拟通过库(发布者)发布的实时市场数据,我的 WPF 客户端是订阅者(具有处理程序方法)。它使用自定义事件来发布数据。
我的问题是这样的:
1)我想实现生产者消费者 - 所以我的处理程序不会直接将数据拉入 Observable Collection。
2) 我确切地知道如何实现生产者/消费者 C# 片段 ( http://msdn.microsoft.com/en-us/library/hh228601.aspx ),但想更多地了解这将如何适合我当前的架构。这是一个图表
3)任何人都可以用代码方法,链接等帮助我吗?
MainWindowViewModel.cs
public class MainWindow_VM : ViewModelBase
{
#region Properties
public myCommand SbmtCmd { get; set; }
public ObservableCollection<StockModel> stocks { get; set; }
#endregion
#region Fields
private readonly Dispatcher currentDispatcher;
#endregion
public MainWindow_VM()
{
SbmtCmd = new myCommand(mySbmtCmdExecute, myCanSbmtCmdExecute);
currentDispatcher = Dispatcher.CurrentDispatcher;
stocks = new ObservableCollection<StockModel>();
}
private void mySbmtCmdExecute(object parameter)
{
MarketDataProvider p = new MarketDataProvider();
p.OnMarketData += new EventHandler<MarketDataEventArgs>(handlermethod);
p.GenerateMarketData();
}
private bool myCanSbmtCmdExecute(object parameter)
{
return true;
}
// Subscriber method which will be called when the publisher raises an event
private void handlermethod(object sender, MarketDataEventArgs e)
{
foreach (Stock s in e.updatedstk)
{
StockModel sm = new StockModel();
sm.symbol = s.symbol;
sm.bidprice = s.bidprice;
sm.askprice = s.askprice;
sm.lastprice = s.lastprice;
currentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
{
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);
}
}
});
}
}
}