Should a return statement be inside or outside a lock?

后端 未结 9 2143
别那么骄傲
别那么骄傲 2020-12-12 18:32

I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?

1)

void exampl         


        
9条回答
  •  离开以前
    2020-12-12 19:20

    It doesn't make any difference; they're both translated to the same thing by the compiler.

    To clarify, either is effectively translated to something with the following semantics:

    T myData;
    Monitor.Enter(mutex)
    try
    {
        myData= // something
    }
    finally
    {
        Monitor.Exit(mutex);
    }
    
    return myData;
    

提交回复
热议问题