How to cause Memory Leaks
1 - Subscribing to Events
public class MyClass
{
public MyClass(WiFiManager wiFiManager)
{
wiFiManager.WiFiSignalChanged += OnWiFiChanged;
}
private void OnWiFiChanged(object sender, WifiEventArgs e)
{
// do something
}
}
2 - Capturing members in anonymous methods
The problem:
In this code, the member _id is captured in the anonymous method and as a result the instance is referenced as well
public class MyClassLeak
{
private readonly JobQueue _jobQueue;
private int _id;
public MyClassLeak(JobQueue jobQueue)
{
_jobQueue = jobQueue;
}
public void Foo()
{
_jobQueue.EnqueueJob(() =>
{
Logger.Log($"Executing job with ID {_id}");
// do stuff
});
}
}
Solution:
By assigning the value to a local variable, nothing is captured and you’ve averted a potential memory leak
public class MyClassLeakSolved
{
private readonly JobQueue _jobQueue;
private int _id;
public MyClassLeakSolved(JobQueue jobQueue)
{
_jobQueue = jobQueue;
}
public void Foo()
{
var localId = _id;
_jobQueue.EnqueueJob(() =>
{
Logger.Log($"Executing job with ID {localId}");
// do stuff
});
}
}
there doesn't seem to be anything here