The following code has a memory leak. If one ProcMat is pushed into the queue, the Step() function will process it, call ClearCache() on it and go back to waiting in the “while (BackgroundQueue.Count == 0)” loop. But, it will not release its reference to the material. Even though the execution exits the if() block and the material variable goes out of scope, it is not released. material must be explicitly set to null at the end of the outer if() block, at the point when it should automatically go out of scope, to avoid the leak.
WTF? Is this expected behavior?
Queue<ProceduralMaterial> BackgroundQueue = new Queue<ProceduralMaterial>();
IEnumerator Step() {
while (true) {
while (BackgroundQueue.Count == 0)
yield return null;
if (BackgroundQueue.Count > 0) {
ProceduralMaterial material = BackgroundQueue.Dequeue();
if (material.isLoadTimeGenerated) {
material.RebuildTextures();
while (material.isProcessing)
yield return null;
material.ClearCache();
}
}
}
}
Simpler example. Same result.
Queue<ProceduralMaterial> BackgroundQueue = new Queue<ProceduralMaterial>();
IEnumerator Step() {
while (true) {
while (BackgroundQueue.Count == 0)
yield return null;
if (BackgroundQueue.Count > 0) {
ProceduralMaterial material = BackgroundQueue.Dequeue();
material.RebuildTexturesImmediately();
}
}
}
Coroutines use a .net/mono feature called an ‘iterator function’.
It’s a function that when called creates an IEnumerable or IEnumerator (depending the return type) based on the code inside the function.
That code actually gets rearranged into a anonymous class type. If you ever reflected it out it’s be like type “ClassFunctionIsIn+d__9” or something similar. You can see it here:
So this anonymous type/class that gets generated. It actually implements the ‘MoveNext’ method of IEnumerator, and every chunk of code between each ‘yield’ statement because a specific ‘state’ of the IEnumerator. When MoveNext is called it runs through the current states code, then returns the yield statement. Unity then waits as long is needed based on that, before calling MoveNext again.
Variables that persist between states would need to be made fields of the class so that they can persist.
Thing is… especially in while loops… it’s not exactly easy to determine that. Furthermore, we’re using an old version of mono which is notorious for cutting corners. I wouldn’t be surprised if it just makes all variables field level members, and not even bother discriminating.
Anyways… that’s the root of your issue.
Iterator functions technically aren’t functions and shouldn’t be considered to scope in the manner functions do.
Rather it’s a function that generates a dynamic object based on the code in the function.
1 Like