Multi threading which helps to call methods parallelly, While executing parallelly first thread will pause while executing the second thread.
Locking: By using lock we can prevent parallel execution, While using lock it will prevent the second thread to execute until first thread completes.
MultiThreading.cs
using System;
namespace CSharpPractices
{
internal class MultiThreading
{
public void DisplayThread()
{
// Creating two threads (Multi Threading)
Thread t1 = new Thread(Display); // Thread 1
Thread t2 = new Thread(Display); // Thread 2
t1.Start();
t2.Start();
}
public void DisplayWithLockThread()
{
// Creating two threads (Multi Threading)
Thread t1 = new Thread(DisplayWithLock); // Thread 1
Thread t2 = new Thread(DisplayWithLock); // Thread 2
t1.Start();
t2.Start();
}
private void Display()
{
for (int i = 0; i <= 3; i++)
{
Thread.Sleep(1000);
Console.WriteLine($"Thread is executed at {i}");
}
}
private void DisplayWithLock()
{
// Lock is used to lock in the Current Thread
lock (this)
{
for (int i = 0; i <= 3; i++)
{
Thread.Sleep(1000);
Console.WriteLine($"Thread is executed at {i}");
}
}
}
}
}
Program.cs
using CSharpPractices;
using System;
namespace CsharpPractices
{
public class Program
{
public Program()
{
}
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine();
MultiThreading multiThreading = new MultiThreading();
// Multi threading without lock will execute the method parallelly
// After First Execution passing the first thread and executing
// the second thread is parallel process
Console.WriteLine("Multi threading without lock");
Console.WriteLine();
multiThreading.DisplayThread();
// With the help of lock it will execute the second thread after
// completing the first thread
Console.WriteLine("Multi threading with lock");
Console.WriteLine();
multiThreading.DisplayWithLockThread();
Console.ReadKey();
}
}
}
Output with out lock: