Skip to content

CacheItemPolicy with HostFileChangeMonitor takes time to clean the cache #38362

Open
@Chizkiyahu

Description

@Chizkiyahu

When I use CacheItemPolicy with HostFileChangeMonitor and the file changed is taking 5-7 ms for cache to remove the item

[TestMethod]
public void TestHostFileChangeMonitor()
{
    var cachedFilePath = @"c:\temp\123.txt";
    File.WriteAllText(cachedFilePath, "1111");
    System.Runtime.Caching.ObjectCache cache = MemoryCache.Default;
    string fileContents = cache["filecontents"] as string;
    if (fileContents == null)
    {
        CacheItemPolicy policy = new CacheItemPolicy();
        List<string> filePaths = new List<string>();
        filePaths.Add(cachedFilePath);

        policy.ChangeMonitors.Add(new
            HostFileChangeMonitor(filePaths));

        // Fetch the file contents.  
        fileContents = File.ReadAllText(cachedFilePath);
        cache.Set("filecontents", fileContents, policy);
    }
    File.WriteAllText(cachedFilePath, "2222");
    int sleepTime = 5;
    Thread.Sleep(sleepTime);
    string fileContents2 = cache["filecontents"] as string;
    Assert.AreEqual("2222", File.ReadAllText(cachedFilePath));
    // the test past only if  sleepTime > 5 
    Assert.IsNull(fileContents2);
}

Pay attention without sleep the test fail with 5-7 ms sleep is past

Configuration

windows 10
visual studio professional
net framework 4.6.1

Analysis

My solution

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions