且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#/.NET中创建内存泄漏

更新时间:2023-02-12 12:57:07

静态事件;致命的,因为它们永远不会超出范围.

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

static event EventHandler Evil;

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

匿名方法在这里只是一个不错的选择,但它很不错,因为它们 也是要取消订阅的猪,除非您将副本复制到变量/字段中并订阅 that .

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.

技术上实际上并不是泄漏",因为您仍然可以通过Evil.GetInvocationList()访问它们-但是,当与常规对象一起使用时,这可能会导致意外的对象寿命,即

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;

现在obj处的对象永远存在.这足以满足IMO的可感知泄漏,并且我的应用程序死于可怕的死亡"对我来说已经足够了; p

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