Junior — Middle
Miks on mõnel juhul oluline mälu vabastamist käsitsi hallata?
sobes.tech AI
Vastus AI-lt
In C# generally the Garbage Collector is used, which automatically frees unused memory. However, in some cases, it is important to manage memory freeing manually:
- When an object uses unmanaged resources (files, network connections, descriptors) that are not controlled by the garbage collector.
- To free resources in a timely manner and prevent leaks and deadlocks.
For this, the IDisposable interface and the Dispose() method are implemented, where resources are explicitly released.
Example:
class FileHandler : IDisposable
{
private FileStream _fileStream;
public FileHandler(string path) {
_fileStream = new FileStream(path, FileMode.Open);
}
public void Dispose() {
_fileStream?.Dispose();
}
}
Thus, manual memory management is important for resource control and preventing performance and stability issues.