我正在 .net
中处理一些图像处理脚本,遇到了 following article概述如何裁剪、调整大小、压缩等。
在first comment , 有人指出文章中用于成像的方法因内存泄漏而臭名昭著:
A quick warning to everybody thinking about using System.Drawing (or GDI+) in an ASP.NET environment. It's not supported by Microsoft and MSDN (as of recently) clearly states that you may experience memory leaks.
然后,在第二条评论中,文章作者有效地说“我已经处理了那个问题”:
Just to make clear the code above isn't thrown together. It evolved with time because as you suggested it is too easy to mistakenly create performance issues when using GDI+. Just see how many times I've written 'using' above!
我想知道如何(或是否)使用 using
有效地处理(或改善)第一条评论中提到的内存泄漏问题。
最佳答案
using
语句不会做任何性能方面的事情。它所做的是在声明了 using
的对象上调用 Dispose
方法。
调用 Dispose
将允许取消分配非托管资源,例如 GDI+ 为您的图像操作创建的资源。这将释放内存和 Windows 句柄。两者都可能导致您的应用程序停止正常工作,因为如果内存或句柄用完,您的程序将无法运行。
using
语句实际上等同于(并最终编译成这样):
var x = ...; // code from using intialization
try
{
... // code inside using statement
}
finally
{
((IDisposable)x).Dispose();
}
这确保了对象被释放,即使发生异常也是如此。
关于c# - "using"关键字如何提高性能(内存或速度方面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35063768/