如何将内存缓存的内容转储到文件

本文关键字:转储 文件 内存 缓存 | 更新日期: 2023-09-27 18:36:09

我想将MemoryCache对象的内容转储到文件中以进行调试。

我该怎么做?

法典:

private static readonly MemoryCache OutputCache = new MemoryCache("output-cache");    
public static void DumpMemoryCacheToFile(string filePath)
{
    try
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        {
            IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(fileStream, OutputCache);
            fileStream.Close();
        }
    }
    catch
    {
        // Do nothing
    }
}

但是这段代码给了我一个运行时错误,说"无法序列化内存缓存"。

如何将内存缓存的内容转储到文件

设法使用这段代码转储密钥。使用 json 进行序列化。

  public static void DumpMemoryCacheToFile(string filePath)
    {
        try
        {
            using (var file = new StreamWriter(filePath, true))
            {
                foreach (var item in OutputCache)
                {
                    string line = JsonConvert.SerializeObject(item.Key);
                    file.WriteLine(line);
                }
            }
        }
        catch
        {
            // Do nothing
        }
    }

转储缓存中的所有对象将创建一个非常大的文件,内容杂乱无章。以上内容足以满足我的需求。

var memoryCache = MemoryCache.Default;
var allObjects = memoryCache.ToDictionary(
    cachedObject => cachedObject.Key,
    cachedObject => cachedObject.Value
);
var contentsAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(allObjects, Formatting.Indented);
System.IO.File.WriteAllText("c:''myCacheContents.txt", contentsAsJson);

这假设了一个非常简单的缓存,其中对象可以轻松序列化(即不包含自引用对象),并且我们不关心在迭代其内容时锁定缓存。