c# - 内存不足时释放的动态变量?

标签 c# .net variables memory-management

背景

所以前提是我有一个类提供一个属性的数据。

class ExampleClass
{
   string _largeCalculatedVariable = null;
   public string largeCalculatedVariable
   {
       get
       {
           if (_largeCalculatedVariable == null)
           {
              _largeCalculatedVariable = LongRunningCalculate();
           }
           return _largeCalculatedVariable
       }
   }
}

该属性隐藏了一个事实,即如果尚未生成数据,则数据可能会即时计算数据,但如果之前已预先计算或计算过,则会返回缓存值。

问题

问题是可能会生成大量 ExampleClass,如果我访问其中足够多的 largeCalculatedVariable,我可能会耗尽内存。因为我可以随时重新计算该值,有没有办法告诉 .NET 在需要内存时删除 _largeCalculatedVariable

注意:我感觉我可能在这里使用了错误的设计模式。

最佳答案

如果您使用的是 .NET 4.0 或更新版本,您可以使用 MemoryCache类,您可以将其设置为具有应存储多少数据的规则,如果达到限制,它将自行清除以腾出空间。

class ExampleClass
{
   //This is a static constructor;
   static ExampleClass()
   {
       var settings = new NameValueCollection();
       settings.Add("PhysicalMemoryLimitPercentage", "75");

       _cache = new MemoryCache("ExampleClassCache", settings);
   }

   private static MemoryCache _cache;

   public ExampleClass()
   {
      _cacheKey = Guid.NewGuid().ToString();
   }

   private readonly string _cacheKey;

   public string largeCalculatedVariable
   {
       get
       {
            var record = _cache.Get(_cacheKey) as string;

            //If record was null that means the item was not in the cache.
            if(record == null)
            {
                record = LongRunningCalculate();
                _cache.Add(_cacheKey, record, new CacheItemPolicy(), null);
            }

           return record;
       }
   }
}

如果您愿意,您还可以让 ExampleClass 在处理对象时从缓存中取出项目以释放​​空间,这不会有太多额外的实现。

class ExampleClass : IDisposable
{
    //...Everything else is the same from the previous code example.

    public void Dispose()
    {
        Dispose(true)
        GC.SupressFinialize(this);
    }

    bool _disposed;

    protected virtual void Dispose(bool disposing)
    {
        if(!_disposed)
        {
            if(disposing)
            {
                //Nothing to do here, we want to remove from the cache if Dispose or the finalizer is called.
                //But you may have IDisposeable objects in your real class, they should be disposed in here.
            }

            if(_cacheKey != null)
                _cache.Remove(_cacheKey, null);

            _disposed = true;
        }
    }

    ~ExampleClass()
    {
        Dispose(false);
    }
}

关于c# - 内存不足时释放的动态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321166/

相关文章:

c# - 更好的求和方式

c# - 递归。并非所有代码路径都返回一个值

c# - Jquery AJAX 与 ASP.NET WebMethod 刷新整个页面

c# - 使用异步 CTP 同时下载 HTML 页面

php - 如何在 PHP 中将两个字符串组合在一起?

c# - 删除文件夹/文件和子文件夹

c# - 无法在 Asp.net Web 窗体应用程序中填充网格 onclick 事件

.net - cf.net 排队等待 web 服务

javascript - 如何在 JavaScript Node.js 中将函数分配给全局变量?

bash - 扩展变量 Bash 脚本