首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >finally块的隐藏功能?

finally块的隐藏功能?
EN

Stack Overflow用户
提问于 2019-11-12 14:49:03
回答 1查看 76关注 0票数 4

我正在阅读source codes for ConcurrentQueue,这时我看到了这个(第790-811行):

代码语言:javascript
复制
//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();
    }
}

在读完那条评论后,我仍然不知道它是什么意思。finally块有什么魔力,官方API会把一个代码块包装到一个有一个空try块的finally块中?有没有一个简单的例子可以解释finally块的这种特殊功能?

EN

回答 1

Stack Overflow用户

发布于 2019-11-12 15:01:37

当finally块正在运行时,不能发生线程中止。您可以通过CLR保证执行。

您发布的代码正在利用这一事实来确保始终执行清理。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58813395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档