using语句-是否触发垃圾回收? [英] using statement - does it trigger garbage collection?

查看:111
本文介绍了using语句-是否触发垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是包装一些可疑函数,这些函数可能会在using语句中泄漏以触发垃圾回收,有人使用过或看到过类似的东西吗?这样行吗?您对此有何看法?

What I'd like to do is wrap some suspect functions that may be leaking in a using statement to trigger garbage collection, has anyone used or seen something like this? Does this work? Whats your thoughts on this?

using (String wrapper = new String("maybe this will trigger gc")){
  //do stuff here
  //or maybe:
  // function1();
  // function2();
  //
  //and then see if its leaking?

  // eg:
       _mygeometry = new Geometry();
       _mygeometry = null; // will GC free this ?
}

您认为这行得通吗?你以前用过这个吗?有什么我可以做的不是String的东西吗?我正在使用WPF,我尝试使用(var waste = 1){},但我认为String可能无法正常工作.

Do you think this will work? Have you used this before? Is there something I can do that isnt a String? Im using WPF, I tried using ( var garbage = 1 ){} and doesnt work, I suppose String might though.

推荐答案

使用语句仅适用于实现 IDisposable 的类>.它只是确保您在using()中定义的对象在执行该块后甚至发生某些异常时都将调用其Dispose方法.这与将tryfinally块一起使用相似.

using statement only works for those classes which implements IDisposable. It just makes sure that the object you defined inside the using() will call its Dispose method after the execution of the block or even when some exception occurs. It is just similar to using try with finally block.

如果您怀疑应用程序中存在内存泄漏,那么最好使用一些可用的内存分析器来检测问题.

If you are suspecting memory leakage in your application then its better if you use some of the available memory profilers to detect the problem.

您不应将当前代码编译为String类未实现IDisposable

Your current code shouldn't compile as String class doesn't implement IDisposable

自修改后的问题

_mygeometry = null; // will GC free this ?

您应该看到此SO链接: C#:应将对象变量分配为null吗? 并从VinayC回答

You should see this SO Link: C#: should object variables be assigned to null? and answer from VinayC

这篇关于using语句-是否触发垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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