我有一个对象可以解析大量实时数据,然后在数据发生变化时触发事件。有时,实时数据可能会失去同步,当检测到这些数据时,它会创建一个新对象实例,以便将所有内容同步备份。
我运行一个监视器线程,确保更新正在进行。它看起来像这样:
private async Task DesyncMonitorThread()
{
while (true)
{
if ((DateTime.Now - _lastOrderBookChange) > TimeSpan.FromSeconds(30))
{
Console.WriteLine("No order book activity in 30 seconds. Dispatching desync handler.");
_lastOrderBookChange = DateTime.Now;
OnDesyncDetected(this, new EventArgs());
}
await Task.Delay(1000);
}
}
OnDesyncDetected方法:
private void OnDesyncDetected(object sender, EventArgs e)
{
//Unsubscribe
Console.WriteLine("Desync detected. Resyncing order book and prediction engine.");
if (_book != null)
{
_book.OrderBookChanged -= OnBookChange;
_book.DesyncDetected -= OnDesyncDetected;
}
if (_predictor != null)
_predictor.PredictionChanged -= OnNewPrediction;
_book = new RealtimeOrderBook(_productId);
_predictor = new MarketPredictor(_book, Settings.PredictorSettings);
_book.OrderBookChanged += OnBookChange;
_book.DesyncDetected += OnDesyncDetected;
_predictor.PredictionChanged += OnNewPrediction;
}
创建新对象可以正常工作,并且Book
和_predictor
新实例中订阅的事件将按预期触发。但是,事件处理程序OnBookChange
,DesyncDetected
和OnNewPrediction
不会。
我想假设这与订阅错误的对象有关,但我无法弄清楚原因。可能是因为这发生在另一个线程上吗?
答案 0 :(得分:-1)
应手动触发自定义事件,因此您可以通过
触发OrderBookChanged,DesyncDetected,PredictionChanged事件 _book = new RealtimeOrderBook(_productId);
_predictor = new MarketPredictor(_book, Settings.PredictorSettings);
_book.OrderBookChanged += OnBookChange;
_book.DesyncDetected += OnDesyncDetected;
_predictor.PredictionChanged += OnNewPrediction;
_book.OrderBookChanged(_book,new EventArgs());
_book.DesyncDetected(_book,new EventArgs());
_predictor.PredictionChanged(_predictor,new EventArgs());
或直接调用方法
_book = new RealtimeOrderBook(_productId);
_predictor = new MarketPredictor(_book, Settings.PredictorSettings);
_book.OnBookChange(para);
_book.OndesyncDetected(para);
_predictor.OnNewPrediction(para);