c# - 为什么要在空 try block 中使用 try {} finally {}?

标签 c# .net

我注意到在 System.Threading.TimerBase.Dispose() 中,该方法有一个 try{} finally{} block ,但是 try{} 为空。

try{}finally{} 与空的 try 一起使用有什么值(value)吗?

http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Threading&type=TimerBase

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal bool Dispose(WaitHandle notifyObject)
{
    bool status = false;
    bool bLockTaken = false;
    RuntimeHelpers.PrepareConstrainedRegions();
    try {
    }
    finally {
        do {
            if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0) {
                bLockTaken = true;
                try {
                    status = DeleteTimerNative(notifyObject.SafeWaitHandle);
                }
                finally {
                    m_lock = 0;
                }
            }
            Thread.SpinWait(1);
            // yield to processor
        }
        while (!bLockTaken);
        GC.SuppressFinalize(this);
    }

    return status;
}

最佳答案

来自 http://blog.somecreativity.com/2008/04/10/the-empty-try-block-mystery/ :

This methodology guards against a Thread.Abort call interrupting the processing. The MSDN page of Thread.Abort says that “Unexecuted finally blocks are executed before the thread is aborted”. So in order to guarantee that your processing finishes even if your thread is aborted in the middle by someone calling Abort on your thread, you can place all your code in the finally block (the alternative is to write code in the “catch” block to determine where you were before “try” was interrupted by Abort and proceed from there if you want to).

关于c# - 为什么要在空 try block 中使用 try {} finally {}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2186101/

相关文章:

c# - 编码(marshal) C# 调用 DLL 库

.net - 不同类型的用户控件的 WPF 列表

c# - 如何在 C# mongo 驱动程序中设置复数集合名称?

c# - 使用Application.Controller MVC

c# - 使用第三方库(带反射)较旧 .NET 版本的 .NET 应用程序

Java/.NET 将垃圾收集器的引用标记为 "do not follow"?

.net - 如何在Visual Studio 2010下将C++/CLI的.NET 4客户端配置文件作为目标?

c# - "111 -> c:\my source\file1.cpp (no code)"的正则表达式 (C#)

c# - 数据库操作预计影响 1 行,但实际影响 0 行

c# - Socket 接收数据时处理未知字节大小