C# 最终块的隐藏函数?
当我看到这个(第790-811行)时,我正在阅读:C# 最终块的隐藏函数?,c#,.net,finally,C#,.net,Finally,当我看到这个(第790-811行)时,我正在阅读: //我们需要在finally块中执行Interlocked.Increment和value/state更新,以确保它们运行 //没有中断。这是为了防止它们之间发生任何事情,以及另一次出列 //线程可能永远旋转,等待m_state[]为真; 尝试 { } 最后 { 新高=联锁增量(参考m_高); 如果(newhigh线程中止不能在finally块运行时发生。CLR保证执行 您发布的代码正利用这一事实来确保始终执行清理。更准确地说,您可以保证代码在
//我们需要在finally块中执行Interlocked.Increment和value/state更新,以确保它们运行
//没有中断。这是为了防止它们之间发生任何事情,以及另一次出列
//线程可能永远旋转,等待m_state[]为真;
尝试
{ }
最后
{
新高=联锁增量(参考m_高);
如果(newhigh线程中止不能在finally块运行时发生。CLR保证执行
您发布的代码正利用这一事实来确保始终执行清理。更准确地说,您可以保证代码在假定域/进程的其余部分不会消失(即有人拔出插头)且线程未挂起的情况下运行。
//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();
}
}