Please go through the following code. It helped me a lot.
https://devblogs.microsoft.com/oldnewthing/20120301-00/?p=8193&nsl_bypass_cache=38b695449cfe09dfbda2fc1e01facf39