Reputation: 97
On my production server I have a heavily used SQL Server instance and my application which is a c# Windows Service. My service runs various jobs at different times. Every 24 hours it sends an email giving updates about the progress of various jobs.
The code determines whether to send the email by checking a flag in the Memory Cache. The code looks like this:-
if (Common.MemCache.Get(Common.MemoryCacheActions.DailyEmail) == null)
{
Common.Logger.Info("Collating email data.");
Common.MemCache.Add(Common.MemoryCacheActions.DailyEmail, String.Empty, DateTime.Now.AddHours(24));
SendEmail();
}
As my main loop checks for the null entry every minute or so, I have been getting lots of emails. It is almost as if the Add has failed, or the item has been evicted?
I have read in places that items can get evicted if there is not enough memory available. As it happens at the time this was happening, a maintenance script was running in SQL Server and available memory on the box was pretty much zero. I closed a few programs I had running on the server, chrome, SSMS etc,, and voila no more log entries, or emails.
As I have explicitly set the Expiration of the item to Now + 24 hours, I would expect it to add the item for 24 hours!
What is the solution here, do I have to set the CacheItemPriority to NotRemoveable and then manually remove the item after 24 hours?
Kind of defeats the point of how I am using my cache, or will NotRemovable work in tandem with the AbsoluteExpirationDate ?
Upvotes: 0
Views: 1181
Reputation: 1
I think, the described behavior is correct - there is no contract or definition saying the item could not be evicted from the cache anytime.
To schedule email once per 24 hours is IMHO much better to use e.g. https://www.quartz-scheduler.net/ or any other scheduling library of your choice.
That would much clearly show your intent.
Upvotes: 0
Reputation: 150108
You can use
MemoryCache.CreateCacheEntryChangeMonitor()
Creates a CacheEntryChangeMonitor object that can trigger events in response to changes to specified cache entries.
to see if the relevant item is removed from the cache.
That method returns a CacheEntryChangeMonitor instance, whose NotifyOnChanged method is used to provide a callback method that is invoked when the cache changes.
Also, verify that your service is not restarting. Perhaps it is crashing and set to restart on crash?
Upvotes: 1