在try / finally之外或之内初始化一次性资源 [英] Initializing disposable resources outside or inside try/finally

查看:173
本文介绍了在try / finally之外或之内初始化一次性资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了两种获取和处理资源的方式。

I have seen two ways of acquiring and disposing resources. Either:

Resource resource = getResource();
try { /* do something with resource */ }
finally { resource.close(); }

或:

Resource resource = null;
try { resource = getResource(); /* do something with resource */ }
finally { if (resource != null) resource.close(); }

我想知道哪种风格更可取。第一个避免了 if 条件,而第二个(我假定)在分配之后,但在进入 try之前处理线程中止的情况阻止。这些风格有什么其他优点和缺点彼此?

I was wondering which style is preferable. The first one avoids the if condition, while the second one (I presume) handles the case of thread abort right after the assignment but before entering the try block. What other pros and cons do these styles have over each other? Which one should I preferably use?

推荐答案

在C#中,只需使用using语句:

In C#, just use the using statement:

using (Resource resource = GetResource())
{
    /* Do something */
}

在分配和进入try块之间不存在Java中线程异常终止的风险 - 只有在睡眠和等待期间才会发生中断。编辑:我实际上不能在规范中找到这,这是有点担心。嗯。

There's no risk of a thread abort in Java happening between the assignment and entering the try block - aborts only occur during sleeps and waits. I can't actually find this in the spec, which is somewhat worrying. Hmm.

这篇关于在try / finally之外或之内初始化一次性资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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