Thursday 5 July 2018

finally block runs always :)

Sometimes the obvious things are easiest things to overlook. Consider the below scenario as an example. I need to ensure that only 1 caller can run a code block at any point in time and other callers should be rejected during that period. Does the below code work correctly then?

public class MyClass
{

private static bool canOthersProcess = true;
private static object obj = new object();

public void MyMethod
{
            try
            {
                // do something
                lock(obj)
                {
                    if (canOthersProcess)
                    {
                        canOthersProcess = false;
                    }
                    else
                   {
                        return;
                    }
               }

               // do something

            }
            catch(Exception)
            {

            }
            finally
            {
                canOthersProcess = true;

            }
}
}

The thing to remember about Finally block is that it always runs :)

Change this to following to make it work correctly.

 try
            {
                // do something
                lock(obj)
                {
                    if (canOthersProcess)
                    {
                        canOthersProcess = false;
                    }
                     else
                   {
                        return;
                    }
                 }

                       //do something
                       canOthersProcess  = true;

            }
            catch(Exception)
            {
                     canOthersProcess  = true;
            }