当我看到 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
块的特殊功能呢?