在事件处理期间交换集合

时间:2016-07-15 11:05:58

标签: c# events collections locking

我正在尝试实现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方法以防止空指针异常?

我尝试过上面的实现,但我不确定它是否足够保存。

0 个答案:

没有答案