How to create a memory leak in C# / .NET [duplicate]

[亡魂溺海] 提交于 2020-01-01 05:32:20

问题


Possible Duplicates:
Is it possible to have a memory leak in managed code? (specifically C# 3.0)
Memory Leak in C#

There was a similar question on this yesterday, but for Java, so I'm interested - what it takes to create a memory leak in C# / .NET (without using unsafe) ?


回答1:


static events; DEADLY, since they never go out of scope.

static event EventHandler Evil;

for(int i = 0 ; i < 1000000 ; i++)
    Evil += delegate {};

The anonymous method is simply a nice-to-have here but are nice because they also are a pig to unsubscribe unless you take a copy into a variable/field and subscribe that.

Technically this isn't actually "leaked", as you can still access them via Evil.GetInvocationList() - however, when used with regular objects this can cause unexpected object lifetimes, i.e.

MyHeavyObject obj = ...
...
SomeType.SomeStaticEvent += obj.SomeMethod;

now the object at obj lives forever. This satisfies enough of a perceived leak IMO, and "my app died a horrible death" is good enough for me ;p




回答2:


When an object subscribes to an event, the object exposing the event maintains a reference to the subscriber (actually, the event, the MultiCastDelegate originally does, but it carries through). This reference will prevent the subscriber from being GC'd if the last reference to it (other than the one maintained by the event) goes out of scope.

The other two answers have this situation completely backward and are incorrect. This is a little tricky to show in a simple example and is typically seen in larger projects, but just remember that a reference to the subscriber is maintained by the MultiCastDelegate (event) and you should be able to think it through.

EDIT: As Marc mentions in his response you could technically get a reference to the "leaked" object via the GetInvocationList() method, but your code is unlikely to be using that and it won't matter when you crash with an OutOfMemoryExcetion.




回答3:


Direct memory access is abstracted away from safe managed code. There has to be a call to unsafe code somewhere in order to induce leaking of memory, either in code you write or in a 3rd party resource (possibly within the FCL) with a memory leak bug.



来源:https://stackoverflow.com/questions/6567916/how-to-create-a-memory-leak-in-c-sharp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!