gpt4 book ai didi

c# - 将 MemoryCache 内容持久化到文件

转载 作者:行者123 更新时间:2023-11-30 12:28:30 27 4
gpt4 key购买 nike

我打算在 Windows 窗体应用程序中使用 .Net 4.0 中引入的强大缓存库。到目前为止,MemoryCache 完成了我需要的一切,除了将其内容保存到文件中。我想要做的是在应用程序退出时将缓存持久保存到一个文件中,然后当应用程序再次打开时,我应该能够从文件中写入并将其内容放入 MemoryCache .我知道我可以简单地将实例序列化为磁盘上的二进制文件,但话又说回来,我不知道如何将它转换回 *MemoryCache*

非常感谢您的帮助。

最佳答案

我最终实现了自己的 Cache 项目。希望这对某个地方的人有帮助:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace CachingDemo
{
class CachedMemory
{
System.Collections.Specialized.OrderedDictionary cache = null;
private String persistenceFilePath = null;
private int cacheSizeLimit;
public static readonly int CACHE_SIZE_NO_LIMIT = -1;

public CachedMemory(int initialCapacity, int cacheSizeLimit, string persistenceFilePath)
{

this.cache = new System.Collections.Specialized.OrderedDictionary(initialCapacity);
this.persistenceFilePath = persistenceFilePath;
this.cacheSizeLimit = cacheSizeLimit;

}

public int getCacheSize()
{
return this.cache.Count;
}

public CachedMemory(int cacheSizeLimit, string cacheFilePath)
{
initializeCache(cacheFilePath, cacheSizeLimit);
}

private void initializeCache(string cacheFilePath, int cacheSizeLimit)
{
this.cacheSizeLimit = cacheSizeLimit;
using (FileStream fileStream = new FileStream(cacheFilePath, FileMode.Open))
{
IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
this.cache = (System.Collections.Specialized.OrderedDictionary)bf.Deserialize(fileStream);
fileStream.Close();
}

//In case the deserialized OrderedDictionary had more contents than the limit, we need to shrink it to make its size equal to the limit
if (this.cacheSizeLimit != CACHE_SIZE_NO_LIMIT && this.cache.Keys.Count > this.cacheSizeLimit)
{
int difference = this.cache.Keys.Count - this.cacheSizeLimit;

for (int i = 0; i < difference; i++)
{
cache.RemoveAt(0);
}
}
}

public string get(string key)
{
return cache[key] as string;
}

public string get(int index)
{
return cache[index] as string;
}


public void add(string key, string value)
{
//An ordered dictionary would throw an exception if we try to insert the same key again, so we have to make sure that the newly
//introduced key is not a duplicate.
if (this.cache.Contains(key))
{
this.cache.Remove(key);

}
else
if (this.cacheSizeLimit != CACHE_SIZE_NO_LIMIT && this.cache.Count == this.cacheSizeLimit)
{
this.cache.RemoveAt(0);

}

this.cache.Add(key, value);
}

public void persist()
{
using (FileStream fileStream = new FileStream(persistenceFilePath, FileMode.Create))
{
IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(fileStream, this.cache);
fileStream.Close();
}
}
}
}

关于c# - 将 MemoryCache 内容持久化到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456215/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com