microsoft / referencesource

Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework
https://referencesource.microsoft.com/
MIT License
3.16k stars 1.27k forks source link

Concurrency Issue with MemoryCache when updating while deleting entry. #89

Closed RuddyR closed 5 years ago

RuddyR commented 5 years ago

I'm working with the MemoryCache library and use the updatecallback delegate to update my cached object. The function OnTimeUpdate is called everytime an cached item expired.

private void OnItemUpdate(CacheEntryUpdateArguments args)

{

    var newItem = NewCopy();
    try
    {

        T _ = newItem.GetItemAsync(null, 
              Info.UpdateMillisecondsTimeout).Result;

 // Insert the new item 
        args.UpdatedCacheItem = new CacheItem(args.Key, newItem);
        args.UpdatedCacheItemPolicy = newItem.GetPolicy();
    }
    catch (Exception)
    {
        args.UpdatedCacheItem = new CacheItem(args.Key, this);
        args.UpdatedCacheItemPolicy = newItem.GetFailedPolicy();
    }
}

The issue is, if another thread is trying to remove the item when the updatecallBack is executed and a new item is calculated. Then when the new item will finish being recalculated, it will replace the expired cache item using args.UpdateCacheItem and add the entry to the cache that supposed to have been removed. Is there a way to make the 2 process coexist and have the remove function stopping the updateCallBack. I thought about using a lock statement to prevent the update while i remove the item, but i dont know if this is the right way to achieve what i want. thks.

terrajobst commented 5 years ago

This repo only tracks infrastructure issues regarding the following items:

For issues regarding functionality, please use the following resources: