utc - C# DateTime.UtcNow value always updated -
i have class should track last time accessed , have public property exposes last access time value set privately.
my class defined follows:
internal class devicemodelcacheitem { private int _cacheid; private list<devicemodel> _devicemodels; private datetime _lastaccess; public devicemodelcacheitem(int cacheid, list<devicemodel> devicemodels) { _cacheid = cacheid; _devicemodels = devicemodels; _lastaccess = datetime.utcnow; } ... public list<devicemodel> devicemodels { { _lastaccess = datetime.utcnow; return _devicemodels; } set { _lastaccess = datetime.utcnow; _devicemodels = value; } } public datetime lastaccess { { return _lastaccess; } } }
i accessing value in seperate class method follows:
var cacheitem = _devicemodelcache.singleordefault(x => x.cacheid == devicetypeid); if(cacheitem != null && datetime.utcnow.subtract(cacheitem.lastaccess).totalseconds > 120) { ... }
where _devicemodelcache collection of devicemodelcacheitem instances.
i'm finding whenever try , access value, private value updated making impossible use tracking value. why being updated?
edit
i've included more code showing how i'm access datetime value. collection of devicemodelcacheitem instances held in singleton follows:
edit 2
i've added db access code , included i'm updating _lastaccess property. figure may have deferred execution problem.
public class devicemodelrepository { private list<devicemodelcacheitem> _devicemodelcache; private static readonly lazy<devicemodelrepository> instance = new lazy<devicemodelrepository>(() => new devicemodelrepository()); public static devicemodelrepository instance { { return instance.value; } } private devicemodelrepository() { _devicemodelcache = new list<devicemodelcacheitem>(); } public ienumerable<devicemodel> getalldevicemodelsbydevicetypeid(int devicetypeid) { return getalldevicemodelsbydevicetypeid(globalconfiguration.app_cache_enabled, devicetypeid); } private ienumerable<devicemodel> getalldevicemodelsbydevicetypeid(bool enablecache, int devicetypeid) { var cacheitem = _devicemodelcache.singleordefault(x => x.cacheid == devicetypeid); //debugger attached here if(cacheitem != null && datetime.utcnow.subtract(cacheitem.lastaccess).totalseconds > 120) { ... using (gadgetcontext db = new gadgetcontext()) { var devicemodels = db.devicemodels.where(x => x.devicetypeid == devicetypeid).tolist(); if (enablecache && devicemodels != null && devicemodels.count > 0) { try { if(cacheitem == null) { _devicemodelcache.add(new devicemodelcacheitem(devicetypeid, devicemodels)); } else { cacheitem.devicemodels = devicemodels; } catch (exception ex) { system.diagnostics.trace.writeline(ex.tostring()); } } } ... } ... } }
as pointed out @jameslucas issue of datetime.utcnow value being updated down deferred execution error in code. date time value being updated every time entity framework deferred execution grab items db.
Comments
Post a Comment