Race Conditions, Deadlocks ⌚⏳

When two or more threads access and trying to change the data at the same time, we call it Race Condition. Because of a thread scheduling algorithm, any task can swap between threads at any point in time, so there is no way to know the order.

In order to understand why race condition even exists or what is it, you have to understand how any real-time ticketing system works. Suppose you have requested an empty seat to book your next journey on a train. You have done it successfully. But when you arrive for your departure, you noticed someone else also booked the very same seat that you had earlier. This is the worst-case scenario on a journey. This is a race condition.

You are going to have a very bad time at any ticketing website if they (developers) didn’t handle race conditions, deadlock.

So I think it should be pretty clear to you what is race condition? right? So how to mitigate this problem right?

There are multiple ways to solve this in C#.

  1. Locks.
  2. Monitor Enter.
  3. Use Immutable Objects.
  4. Don’t use shared objects between multiple threads.


When multiple threads are locked in their state because they are waiting for each other to finish.

class Deadlock { { object lock1 = new object(); object lock2 = new object(); Console.WriteLine("Starting..."); var task1 = Task.Run(() => { lock (lock1) { Thread.Sleep(1000); lock (lock2) { Console.WriteLine("Finished Thread 1"); } } }); var task2 = Task.Run(() => { lock (lock2) { Thread.Sleep(1000); lock (lock1) { Console.WriteLine("Finished Thread 2"); } } }); Task.WaitAll(task1, task2); Console.WriteLine("Finished..."); } }

There are multiple ways to solve deadlocks.

  1. Try not to use nested locks.
  2. Try to use Timeout in Monitor.TryEnter.
  3. If nested locks are necessary, try to change the locking order.

Happy Threading 🕒🕞

Originally published at https://pritompurkayasta.me.

if you like the content, you know what to do 🎉✔