简体   繁体   English

当我使用using对象时,我应该在退出using块之前处置该对象吗?

[英]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.

相关问题 在退出我的方法范围之前,我应该真正处理我的对象吗? - should I really dispose my object before exiting the scope of my method? 如果我在方法中的using块内返回一个值,那么在返回之前是否使用了dispose对象? - If I return a value inside a using block in a method, does the using dispose of the object before the return? 我应该在分配新对象之前处置旧对象吗? - Should I dispose old object before assigning new object? 为什么可以使用using但不能使用object.dispose()? - Why can I use using, but not object.dispose()? 防止 object 使用块在内部处理 - Prevent object dispose inside using block 什么时候可以锁定我正在使用的对象,什么时候应该使用专用的同步锁对象 - When is it acceptable to lock the object I'm using and when should I use a dedicated synclock object 我应该如何正确处置物体? - How should I correctly dispose of an object? 使用Entity Framework Core时应该处置DbContext吗 - Should I dispose DbContext when using Entity Framework Core 如果using语句抛出异常,我如何处置IDisposable对象? - How do I dispose an IDisposable object if the using statement throws an exception? 在它自己的 using 块中处理一个对象不是多余的吗? - Isn't it redundant to dispose of an object inside its own using block?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM