Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate use of Monitor.Exit

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:

  • Assume thread 1 is at //This point
  • Another thread enters Monitor.Enter while thread 1 is still at //This point
  • Will this stop 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.

like image 848
SimpleOne Avatar asked Jan 21 '23 03:01

SimpleOne


2 Answers

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.

like image 152
Dan Bryant Avatar answered Jan 31 '23 22:01

Dan Bryant


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.

like image 21
Frank Liao Avatar answered Jan 31 '23 23:01

Frank Liao