Lock statement vs Monitor.Enter method

前端 未结 2 951
情歌与酒
情歌与酒 2020-12-02 16:43

I suppose that this is an interesting code example.

We have a class -- let\'s call it Test -- with a Finalize method. In the

2条回答
  •  既然无缘
    2020-12-02 17:43

    It is because the reference pointed to by test1 is assigned to the local variable CS$2$0000 in the IL code. You null out the test1 variable in C#, but the lock construct gets compiled in such a manner that a separate reference is maintained.

    It is actually quite clever that the C# compiler does this. Otherwise it would be possible to circumvent the guarentee the lock statement is supposed to enforce of releasing the lock upon exiting the critical section.

提交回复
热议问题