我正在尝试实现ObservationStorage
类,它应该将数据保存到正确的集合取决于当前的YearMonthDay
。新观察请求通过OnDataOccured
方法处理的事件来到我的存储对象。
public class ObserversDataStorage : MarshalByRefObject
{
private object _lock = new object();
public Dictionary<YearMonthDay, DailyObserverStorage> Storage { get; set; }
public ObserversDataStorage()
{
this.Storage = new Dictionary<YearMonthDay, DailyObserverStorage>();
}
public void OnDataOccured(object sender, Common.Observer.AbstractQueryResult e)
{
var ymd = YearMonthDay.FromUTCMiliseconds(e.From);
if (this.Storage.Keys.Contains(ymd))
{
this.Storage[ymd].OnDataOccured(sender, e);
}
else
{
this.Storage.Add(ymd, new DailyObserverStorage(ymd));
this.Storage[ymd].OnDataOccured(sender, e);
}
}
public Dictionary<YearMonthDay, DailyObserverStorage> ChangeStorage()
{
Dictionary<YearMonthDay, DailyObserverStorage> toReturn;
lock (_lock)
{
toReturn = this.Storage;
this.Storage = new Dictionary<YearMonthDay, DailyObserverStorage>();
}
return toReturn;
}
}
我的问题是:
在处理ChangeStorage
请求时,我应该如何实现OnDataOccured
方法以防止空指针异常?
我尝试过上面的实现,但我不确定它是否足够保存。