小编典典

为什么将try {}最终{}与空的try块一起使用?

c#

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

try{} finally{}与空值一起使用是否有任何价值try

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;
}

阅读 554

收藏
2020-05-19

共1个答案

小编典典

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

这种方法可以防止Thread.Abort调用中断处理。Thread.Abort的MSDN页面说:“未执行的最终块在线程中止之前已执行”。因此,为了确保即使有人在线程上调用Abort中断了您的线程而在中间中断了处理,您也可以将所有代码放在finally块中(另一种方法是将代码写入“
catch”块中,以确定在“尝试”被Abort打断之前您在哪里,然后从那里继续进行)。

2020-05-19