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#.
In this chapter you will learn: