0

I have used the Code below. I tried to dispose the memory using the Close() but it is not clearing. Please suggest me on this.

internal static void ToNDJson(List<Metrics> jsonItems)
    {
        using (var textWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\File.json"))
        {
            ToNewlineDelimitedJson(textWriter, jsonItems);
        }
    }

 internal static void ToNewlineDelimitedJson(TextWriter textWriter, List<Metrics> jsonItems)
    {
        var serializer = JsonSerializer.CreateDefault();

        foreach (var item in jsonItems)
        {
            using (var writer = new JsonTextWriter(textWriter) { CloseOutput = false })
            {
                serializer.Serialize(writer, item);
            }

            textWriter.Write("\n");
        }
        textWriter.Close();
    }
dbc
  • 91,441
  • 18
  • 186
  • 284
  • what do you have in mind by not clearing? there is a method Flush that you should call before Close it will dump all buffered data to the underlying stream. If you by clearing think about memory you must know that garbage collector is lazy and will not react immediately. – Rafal Feb 08 '22 at 08:37
  • Hello Rafal, I tried the Flush method for memory clearing, but it didn't work. I have also ensured it with some delay. – Bharathi R Feb 08 '22 at 09:05
  • What exactly is the problem? What do you mean with "dispose memory"? Memory in c# is garbage collected. You dispose *objects* to ensure the program works correctly. And just disposing objects should in general be sufficient, explicit usage of flush/close is usually not needed. – JonasH Feb 08 '22 at 09:27
  • What does "not clearing" mean? Is the data not saving? – Charlieface Feb 08 '22 at 10:19
  • I have used the VisualStudio Diagnostic tool to find the memory leak in my application and i observed that the above code "serializer.Serialize(writer, item);" has memory leak of 100kb. so i tried to dispose it using the Flush , Clear and Dispose methods but the memory leak is not reduced. Please advise how I may reduce JsonSerializer's memory use. – Bharathi R Feb 08 '22 at 13:45
  • Json.NET caches and reuses contract information. That cache explains the "leak" you are seeing inside `serializer.Serialize(writer, item);`. See [Does Json.NET cache types' serialization information?](https://stackoverflow.com/q/33557737/3744182). I don't see any leak in your handling of streams and streamwriters. In fact this looks to be a duplicate, agree? – dbc Feb 26 '22 at 18:37

0 Answers0