I C # in shared objects is destroyed when the GC wants to do this, there is no way to get it to do this. Although this is lazy, I would not let your memory run away. Therefore, the objects that you expect to destroy are not ready for collection. Not ready, I mean that in your application you have a link to this object. Some of these links are obvious as a field in the class that lives throughout the process, others are more difficult to consider:
class LongLivingClass // say main window or some other // instance that lives considerably longer then the other { public event Action SomeEvent; } class ShortLivingClass // class that is created and should be destroyed // many times throughout life of LongLivingClass { ShortLivingClass(LongLivingClass llc) { llc.SomeEvent += DoSomething; } void DoSomething(){
If a ShortLivingClass attaches to an event LongLivingClass , then it will not be destroyed unless you remove this handler in the dispose method:
void Dispose() { llc.SomeEvent -= DoSomething; }
Note that the IDisposable interface is part of a template that is not executed at run time, such as destructors. You need to determine the place and time to call him.
Also remember the closure that your variables will capture, and if these variables are instance fields, then the instance will also be captured.
In the long run, you need to search the Internet for memory leaks in C #. There are many questions on SO that consider this a success.
source share