C#中的foreach循环实例? [英] C# instantiate in foreach loop?

查看:180
本文介绍了C#中的foreach循环实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

循环和垃圾收集




 的foreach(ObjectTypeA在ObjectTypeACollection TYPEA )
{
变种objectTypeAProcessor =新objectTypeAProcessor();
objectTypeAProcessor.Process(TYPEA);
}



我发现那里正被处理过的对象的集合上面类似的代码BLL和DAL处理器是called.Will上面的代码导致内存泄漏/是不是不好?那么一个新的实例被创建每次都正确的,但它是一次比一次销毁呢?嗯...


解决方案

有没有办法知道是否会有泄漏,因为我们不知道是什么 objectTypeAProcessor 一样。如果,例如,它预订另一个对象的一些事件,并且不unsubsribes,或添加到自身的引用另一目的,一个将参考保留在objectTypeAProcessor,所以它不会被收集。



如果内部实现objectTypeAProcessor允许它(这可能并非如此),这将是更好的初始化它只有一次,外循环。


Possible Duplicate:
Loops and Garbage Collection

foreach (ObjectTypeA typea in ObjectTypeACollection) 
{
var objectTypeAProcessor= new objectTypeAProcessor();
objectTypeAProcessor.Process(typea);
}

I found the above similar code where a collection of objects was being processed at the BLL and the DAL processor was called.Will the above code lead to a memory leak / is it bad? Well a new instance is created each time right but does it get destroyed each time too? mmm...

解决方案

There is no way to tell whether there will be a leak, because we don't know what objectTypeAProcessor does. If, for instance, it subscribes to some event of another object and doesn't unsubsribes, or adds a reference to itself to another object, a reference will be kept on the objectTypeAProcessor, so it won't be collected.

If the internal implementation of objectTypeAProcessor allows it (which might not be the case), it would be better to instantiate it only once, outside the loop.

这篇关于C#中的foreach循环实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆