How to avoid Memory Leaks? [closed]

2019-03-15 10:52发布

What are some tips I can use to avoid memory leaks in my applications? Are there any gotchas or pitfalls that I can look out for?

18条回答
萌系小妹纸
2楼-- · 2019-03-15 11:38
  1. Wrap anything which is disposable in a using construct.
  2. Avoid COM objects.
  3. Check to see that all event hanlders are being removed properly.
  4. Check to see that all data bindings are being removed properly.
  5. Keep it simple

If your application logic is getting needlessly complex, you might start ending up with memory leaks. If you keep your classes small and follow general coding practices you probably won't run into any memory leaks with managed code. It is possible, but not as likely as it use to be.

If you suspect a memory leak, use a profiler to see if any objects are being kept around longer than needed.

The last time I ran into a serious memory leak was .NET 1.1, it turned out there was a bug in the framework.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-15 11:39

Call Dispose on IDisposable objects or use the using clause. That should take care of most of the leaks I can think of.

查看更多
唯我独甜
4楼-- · 2019-03-15 11:39

Types which implement a finalizer may leak, if any one finalizer blocks for some reason. I have seen finalizers block due to locking and thread apartment issues.

As instances of types with finalizers are not collected until their respective finalizers have run a single blocking finalizer will block any other finalizable objects pending collection.

查看更多
forever°为你锁心
5楼-- · 2019-03-15 11:41

As mentioned by ocdecio be sure to call Dispose on Idisposable objects, and remember to remove event handlers when you're done with an object. When building classes that works with unmanaged resources, be sure to implement Idisposable, so the user will know that there are critical resources that'll need to be disposed of.

Also, even though garbage collections do quite a bit a work for you, you should get rid of references to objects that you're done with. Else they'll still have a root, and they won't be GC'ed.

查看更多
Luminary・发光体
6楼-- · 2019-03-15 11:41

Most memory leaks that I have encountered in .NET has been related to using COM objects and not releasing them properly. As soon as I see a reference to a COM object, I think "memory leak".

查看更多
smile是对你的礼貌
7楼-- · 2019-03-15 11:41
登录 后发表回答