c# - "using"关键字如何提高性能(内存或速度方面)

标签 c# asp.net .net image-processing memory-leaks

我正在 .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/

相关文章:

c# - c# 上的 Appium 驱动程序错误 :Using the generic type Appium. AppiumDriver<W>' 需要 1 个类型参数

c# - 如何允许人们将 HTML 输入文本框

c# - Elasticsearch.net NEST无法过滤URL

c# - 增加文本框大小 Bootstrap (ASP.NET MVC)

javascript - asp.net Dropdownlist 条件回发

c# - 控制台应用问题

c# - 指定的强制类型转换无效 – SQL float to C# double

asp.net - sisoDB是否使用sql server数据库来存储数据

c# - HTML敏捷包: get all elements by class

c# - 如何将依赖注入(inject)与 Facade 模式一起使用?