Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unlock a thread within lock brackets

I am trying to convert this C++ code into a C#:

do{
    if (Node->NextNode == NULL) WaitForSingleObject(pThis->_Event, INFINITE);
    _critSect.Lock();
    if (Node->NextNode == NULL && !bRunning ) 
    {
        _critSect.Unlock(); // can explicitly unlock here
        break;
    }
    _critSect.Unlock();
}while (Node->NextNode == NULL);

In C++, I can explicitly unlock the thread, but C# only has a bracket. How can I add the "unlock" function in the code below before breaking?

do{
   if (Node->NextNode == null) DataQueueEvent.WaitOne();
   lock (thisLock)
   {
      if (Node->NextNode == null && !bRunning)
      // need to unlock here!!!                      
      break;
   }
} while (Node->NextNode == null);
like image 216
Nazar Avatar asked Dec 05 '25 11:12

Nazar


1 Answers

It's simply unnecessary. in C# the lock statement translates into a try/finally, so the lock will be released whenever you exit the block regardless of how you exit the block, so there's no need to explicitly release the lock when you exit using the break path.

like image 100
Servy Avatar answered Dec 07 '25 00:12

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!