gpt4 book ai didi

c# - finally block 的隐藏功能?

转载 作者:行者123 更新时间:2023-11-30 15:50:55 25 4
gpt4 key购买 nike

<分区>

我正在阅读 source codes for 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();
}
}

看完那条评论,我还是不明白这是什么意思。 finally block 有什么魔力,官方 API 会将代码块包装到 finally block 中,而 finally block 有一个空的 try block ?有没有一个简单的例子可以解释 finally block 的这个特殊功能?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com