CAN"使用"与多个资源导致资源泄漏? [英] Can "using" with more than one resource cause a resource leak?
问题描述
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 formusing (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屋!