finally块的隐藏功能是什么?

4

当我看到 ConcurrentQueue 的源代码 时,发现了这个(第790-811行):

//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
    newhigh = Interlocked.Increment(ref m_high);
    if (newhigh <= SEGMENT_SIZE - 1)
    {
        m_array[newhigh] = value;
        m_state[newhigh].m_value = true;
    }

    //if this thread takes up the last slot in the segment, then this thread is responsible
    //to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
    //if thread abort during Grow, other threads will be left busy spinning forever.
    if (newhigh == SEGMENT_SIZE - 1)
    {
        Grow();
    }
}

阅读了那个评论后,我仍然不知道它的含义。官方API会将一段代码包装在一个只有空的try块的finally块中,这个finally块有什么魔力呢?有没有简单的例子可以解释finally块的特殊功能呢?
1个回答

4
在执行 finally 块时,线程不会中止。由CLR保证必须执行该块。
您发布的代码利用了这一点,以确保始终执行清理操作。

1
更准确地说,假设域/进程的其余部分不会消失(即有人拔掉插头),并且线程没有被挂起,您可以保证代码运行。 - Luaan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接