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()
     {  
          //…
     }
}

 

 

 

 

 

Sponsored Post Learn from the experts: Create a successful blog with our brand new courseThe WordPress.com Blog

Are you new to blogging, and do you want step-by-step guidance on how to publish and grow your blog? Learn more about our new Blogging for Beginners course and get 50% off through December 10th.

WordPress.com is excited to announce our newest offering: a course just for beginning bloggers where you’ll learn everything you need to know about blogging from the most trusted experts in the industry. We have helped millions of blogs get up and running, we know what works, and we want you to to know everything we know. This course provides all the fundamental skills and inspiration you need to get your blog started, an interactive community forum, and content updated annually.