c# - 具有多个资源的 "using"会导致资源泄漏吗?

标签 c# using using-statement

C# 允许我执行以下操作(来自 MSDN 的示例):

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

如果 font4 = new Font 抛出会发生什么?据我了解,font3 会泄漏资源并且不会被处理掉。

  • 这是真的吗? (font4 不会被丢弃)
  • 这是否意味着应该完全避免 using(... , ...) 以支持嵌套使用?

最佳答案

没有。

编译器将为每个变量生成一个单独的 finally block 。

spec (§8.13) 说:

When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A using statement of the form

using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement 

is precisely equivalent to a sequence of nested using statements:

using (ResourceType r1 = e1)
   using (ResourceType r2 = e2)
      ...
         using (ResourceType rN = eN)
            statement

关于c# - 具有多个资源的 "using"会导致资源泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118201/

相关文章:

c# - 为什么我找不到 RadioButtonFor 方法?

c++ - 什么时候使用 using 声明?

c# - 什么是 C# Using block ,我为什么要使用它?

c# - Ok() 怎么可能既是 Task<IActionResult> 又是 IActionResult?

c# - itextSharp - 合并 pdf 文件会禁用扩展阅读器权限

vb.net - 哪个更快 - 使用 block 或 Try/Catch/Finally

c# - 在 Using 语句中创建 ObjectContext 时出现 NullReferenceException

c# - C#中 "using"有什么用?

c# - c# 编译器是否会执行多个隐式转换以从一种类型转换为另一种类型?

c# - 使用嵌套选择 LINQ 循环数组