C# manual lock/unlock

前端 未结 5 2247
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 08:25

I have a function in C# that can be called multiple times from multiple threads and I want it to be done only once so I thought about this:

class MyClass
{
          


        
5条回答
  •  孤城傲影
    2020-12-01 08:51

    The lock keyword is just syntactic sugar for Monitor.Enter and Monitor.Exit:

    Monitor.Enter(o);
    try
    {
        //put your code here
    }
    finally
    {
        Monitor.Exit(o);
    }
    

    is the same as

    lock(o)
    {
        //put your code here
    }
    

提交回复
热议问题