Skip to content

JsonSerializer deserialize big json in tasks memory leak #74725

@zxcvqwerasdf

Description

@zxcvqwerasdf

Description

When you try to deserialize big json file (86kb+) in many tasks with delay you get memory leak

Reproduction Steps

        public static void BugReproduce()
        {
            var taskRequestNonAsync = new HttpClient().GetStringAsync("https://pastebin.com/raw/Dnf2mj1Y"); //86kb J
            taskRequestNonAsync.Wait();
            string readed = taskRequestNonAsync.Result;
            Stopwatch st = new Stopwatch();
            st.Start();
            Task[] tasks = new Task[1000];
            for (int x = 0; x < tasks.Length; x++)
            {
                tasks[x] = Task.Run(async () =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        var root = JsonSerializer.Deserialize<JsonElement>(readed);
                        await Task.Delay(100);
                    }

                });

            }
            Task.WaitAll(tasks);
            st.Stop();
            Console.WriteLine(st.Elapsed.ToString());
            Console.Read();
        }

Expected behavior

No memory leak

Actual behavior

Memory leak

Regression?

No response

Known Workarounds

No response

Configuration

Net 5.0, 6.0, 7.0
x64
Debug/Release

Other information

It's only leak with tasks, in one task it works without any problem. I think this is due to the simultaneous access to the JsonSerializer from several tasks.
here is memory snapshot image
As you can see there is a big Byte[] allocation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions