MethodImplAttribute -Easy way to Synchronize

Sometimes when we try to synchronize a method of a .Net class we need to consider lots of stuff. And sometimes it really becomes complicated to synchronize a method.  But if we come to a conclusion that only one thread will be accessing a particular method at a single point of time then there is a really faster way to Synchronize it –

Using attributes of System.Runtime.CompilerServices namespace , we can change runtime behavior of CLR. MethodImplAttribute is one of such kinda attribute by using which CLR can be notified how the method was implemented. MethodImplAttribute accepts one parameter called MethodImplOptions.

MethodImplOptions has one field – MethodImplOptions.Synchronized that actually tells the compiler only one thread can access the method at any point of time. This is like lock keyword but only difference is that here we are locking the whole method. Let’s have look at one simple example –

public class DemoMethodImpl
{
     [MethodImpl(MethodImplOptions.Synchronized)]
     public void MethodToSyncronize()
     {  
          //…
     }
}