[英]When I use a using object should I dispose this object before exiting the using block?
When I use a using clause on an object should I dispose this object before exiting the using block? 当我在对象上使用using子句时,我应该在退出using块之前处置该对象吗?
using (var transaction = TransactionUtils.CreateTransactionScope())
{
try
{
_entity.Save(entity);
transaction.Complete();
}
catch // or better finally
{
transaction.Dispose(); // Is this try-catch usefull?
throw;
}
}
Note : A similar question has already been asked but I find the example and the answers strange. 注意:已经提出了类似的问题,但是我发现示例和答案很奇怪。
Your transaction will be disposed automatically when exiting the using block. 退出using块时,您的交易将自动进行处理。
This works under the hood like a try-finally block. 这在引擎盖下像尝试最终块一样起作用。
So there is no need to dispose the transaction manual from your code 因此,无需从您的代码中处置交易手册。
It is redundant to dispose the object. 放置对象是多余的。
using (ResourceType resource = CreateResource())
{
DoStuffWith(resource);
}
is equivalent to 相当于
ResourceType resource = CreateResource();
try
{
DoStuffWith(resource);
}
finally
{
if (resource != null)
{
((IDisposable)resource).Dispose();
}
}
For non-nullable value types the null-check is omitted and dynamic
is handled slightly different, too. 对于非空值类型,将省略空检查,并且
dynamic
处理方式也稍有不同。 See 8.13 in the C# Language Specification for more details. 有关更多详细信息,请参见C#语言规范中的8.13。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.