CAN"使用"与多个资源导致资源泄漏? [英] Can "using" with more than one resource cause a resource leak?

查看:163
本文介绍了CAN"使用"与多个资源导致资源泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#允许我做以下(从MSDN示例):

 使用(字体font3 =新的字体(宋体,10.0f)
            font4 =新的字体(宋体,10.0f))
{
    //使用font3和font4。
}

如果 font4 =新字体抛出,会发生什么?据我了解font3会泄漏资源,不会被处理。


  • 这是真的吗? (font4不会被处理)

  • 这是否意味着使用(...,...)应完全避免赞成使用?
  • 的嵌套

解决方案

没有。

该编译器会为每个变量单独的最后块。

借助规范(§8.13)说:


  

在资源采集采用的形式
  局部变量声明,有可能获得多
  给定类型的资源。 A 的形式使用语句

 使用(的ResourceType R1 = E1,R2 = E2,...,RN = EN)语句


  
  

为precisely
  相当于使用嵌套语句序列

 使用(的ResourceType R1 = E1)
   使用(的ResourceType R2 = E2)
      ...
         使用(RN的ResourceType = EN)
            声明


C# lets me do the following (example from MSDN):

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

What happens if font4 = new Font throws? From what I understand font3 will leak resources and won't be disposed of.

  • Is this true? (font4 won't be disposed of)
  • Does this mean using(... , ...) should be avoided altogether in favor of nested using?

解决方案

No.

The compiler will generate a separate finally block for each variable.

The spec (§8.13) says:

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

这篇关于CAN"使用"与多个资源导致资源泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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