How can I replace this code:
try
{
lock (lockForSomethingInUse)
{
somethingInUse = true;
// use it
}
}
finally
{
somethingInUse = false;
}
With:
using (lockForSomething)
{
// use it
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to use
lockand be able to know whether lock is actually acquired at the moment with using only one statement/variable, you can try using following classes. They won’t win you any awards for readability, but they allow you to useusingfor locking as you wanted.The usage:
You can then use
lockForSomething.IsAcquiredin some other place to check if resource is being used. The inner class implementingIDisposableis to make sure you won’t by accident useusing (lockForSomething).