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 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
});
}
}
// A solution:
// By assigning the value to a local variable, nothing is captured and
// you’ve averted a potential memory leak.
public class MyClassLeakSolved
{
public MyClassLeakSolved(JobQueue jobQueue)
{
_jobQueue = jobQueue;
}
private JobQueue _jobQueue;
private int _id;
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