【问题标题】:File Changes don't expire Cache文件更改不会过期缓存
【发布时间】:2021-09-13 16:26:12
【问题描述】:

我正在尝试使用 .NET Core 5.0 缓存 XML 文件。

我正在改编此页面中的示例 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/change-tokens?view=aspnetcore-5.0

我有以下代码,成功缓存文件(不是每次都从磁盘加载),但是当文件更改时,文件内容不会重新缓存。

public XmlDocument loadXML(string strFileName) {
            XmlDocument xml;


            // Try to obtain the file contents from the cache.
            if (_cache.TryGetValue(strFileName, out xml)) {
                return xml;
            }
            xml = this.createNewDocument();

            xml.Load(strFileName);

            if (xml != null) {
                var changeToken = _fileProvider.Watch(strFileName);

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                        .SetSlidingExpiration(TimeSpan.FromMinutes(5))
                        .AddExpirationToken(changeToken);

                // Put the file contents into the cache.
                _cache.Set(strFileName, xml, cacheEntryOptions);
            }
            return xml;
        }
    }

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    我想通了,希望这对将来的人有所帮助。

    我将像“d:\website\file.xml”这样的完全限定文件名作为“strFileName”传递。这是正确加载 XML 所必需的。

    但是 _fileProvider.Watch() 方法需要一个相对 URL,而不是限定文件名,所以在这种情况下它需要是“/file.xml”。

    所以我将 "d:\website\file.xml" 转换为 "/file.xml" 并调用 _fileProvider.Watch( "/file.xml" );

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多