void MethodA()
{
Monitor.Enter(this);
if(someCondition)
{
Monitor.Exit(this);
// This point
MethodB();
}
else
{
// Set some values only
Monitor.Exit(this);
}
}
If I have the above method which can be called in multi threads:
//This point
Monitor.Enter
while thread 1 is still at //This point
MethodB
from being executed? If yes, is there a way of getting MethodB
to execute.I need to release MethodA
before executing MethodB()
because I can't wait for MethodB
to complete before releasing MethodA
. Also, I cannot start MethodB
in a new thread.
Setting aside the issue of using 'this' as a lock (bad practice, as it exposes the lock publically), this form is cleaner and safer (releases the lock if exception is thrown):
void MethodA()
{
bool condition;
lock(this)
{
condition = someCondition;
if(!condition)
{
// Set some values only
}
}
if (condition)
MethodB();
}
To answer your specific question, both this code and your original code will execute MethodB, even if something else acquires the lock.
Since, someCondition is not passed as a parameter, I could only assume the someCondition could be changing at any time (possibly an instance variable to the class). So, I would write the code this way:
void MethodA()
{
if (someCondition)
{
bool conditionReached = false;
Monitor.Enter(this);
try
{
if (someCondition)
{
conditionReached = true;
}
}
finally
{
Monitor.Exit(this);
}
if (conditionReached)
{
MethodB();
}
}
}
If not, than the previous answer with condition
declared locally would suit you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With