Memory leak when copying native queue to native array

I have this system that runs fine in 3.0a5 but when I upgrade it just eats up more and more memory until it crashes the computer. I’ve reduced it to the following example. The longer it runs the larger NativeArray gets in the memory profile. As far as I can tell I’m not doing anything wrong here. All the arrays are disposed of.

using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;

public class FillArrayFromQueueSystem : ComponentSystem
{
    public struct FillArrayJob<T> : IJob where T : struct
    {
        internal NativeQueue<T> Queue;
        internal NativeArray<T> Array;
        public void Execute()
        {
            int index = 0;
            T item;
            while (Queue.TryDequeue(out item))
            {
                Array[index] = item;
                index++;
            }
        }
    }
   
    protected override void OnUpdate()
    {

        NativeQueue<int> queue = new NativeQueue<int>(Allocator.TempJob);
        for (int i = 0; i < 100000; i++)
        {
            queue.Enqueue(i);
        }
        NativeArray<int> array = new NativeArray<int>(queue.Count, Allocator.TempJob);
        var fillJob = new FillArrayJob<int>
        {
            Queue = queue,
            Array = array
        }.Schedule();
        fillJob.Complete();

        queue.Dispose();
        array.Dispose();
    }
}



You should make a bug report and post Issue ID here.

Case 1177449

Replicated this too, in 2019.1.8f1, but I can’t seem to find case 1177449 to vote for it…?

BTW thank you for replicating this I was starting to wonder if I’d gone crazy.

https://fogbugz.unity3d.com/default.asp?1177449_0t5f2202reedvqtr

Same, I’m really glad you posted this since it took me a bit to realize it was the conversion from NativeQueue to NativeArray that was causing my issue and I was losing my mind, lol. No errors or anything, just monitoring memory usage reveals the ever-increasing allocations that are never deallocated, totally unclear why something that should not be referenced/in scope was holding onto memory.

EDIT: This issue is unrelated to jobs, by the way. I took the same code and just inlined it, same exact issue, at least in 2019.1.8f1, so it appears to be an issue with either NativeArray or NativeQueue itself.

They refactored some of the internal queue implementation and it’s had memory leaks ever since. This isn’t the only context it shows up in. This was reported in the DOTS forum also.

Thank you for reporting this! The devs are looking into it. You will shortly be able to find it here on the issue tracker: https://issuetracker.unity3d.com/product/unity/issues/guid/1177449/