C# Lock Statement

In this chapter you will learn:
  • What is Lock Statement in C#?
  • What is the benefit of using lock statement in C#?
  • How to use it in C# programming?

The lock statement handles lock segment as a critical section and locks the object during the execution of the program from other thread. Once the execution is completed it releases the lock and frees objects.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lock_Statement
{
    class Program
    {
        public void printname()
        {
            Console.WriteLine("My name is Steven Clark");
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            // creating lock segment. all the resources that is used in lock segment, can't be used by another thread until it releases.
            lock (p)
            {
                p.printname();
            }
            Console.ReadLine();
        }
    }
}

Output

My name is Steven Clark
__

Summary

In this chapter, you learned what Lock statement is in C# and how to use it in C# programming. In next chapter you will learn about Using Statement in C#.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.