DEV Community

loading...

Solve the scenario - using Thread synchronization in Dotnet

Debashish Pal
I am Debashish Pal. Technical Architect by Profession, A Passionate Coder, Tech lover, Mad for Table Tennis. Love listening to Bollywood music !!
・2 min read

Use Case:

Consider this hypothetical scenario. We need to simulate a Marathon Race. So, we have two entities Race & Player

Race:

  1. Should be able to add the players
  2. Should be able to start the race
  3. It should inform when race starts
  4. It should inform when race ends

Player:

  1. It should have a name
  2. It should declare the fatigue level. Lower is the fatigue, faster the player will run.
  3. It should inform when player starts running
  4. It should inform when player finished the race

Scenario 1:
When race starts it should wait for all the players to finish the race. Race will only end after that.

All players have a consolation price !!

Scenario 2:
When race starts it should wait for the first three winners !! Race ends after it.

Only first three winners will get a price!! Sorry about other folks.

Take a pause

Think about the solution

?

Think again

Scroll down for the solution

...

...

...

...

...

...

Solution

Run the below code in Linqpad (https://www.linqpad.net/), to see it working.

Make sure you press Ctrl+Shift+M, and add the namespace imports i.e. System.Threading & System.Threading.Tasks

We will be using TPL (Task Parallel Library) and Thread Synchronization constructs to solve the problem.

Scenario 1

Alt Text

If you see the output above, the player who is having the lowest fatigue level comes first and one who comes last is having the highest fatigue.

In this solution we are using Task.WaitAll() to wait for all the players to finish the race, before we end it.

Scenario 2

Alt Text

In this solution we are using CountDownEvent. As soon as first 3 players finishes the race it will signal the event, and it's counter will be reduced by one, by each of the players. Since the Race is waiting on CountDownEvent, as soon as it's counter reaches 0, the race would end.

I hope you have understood how to use synchronization to solve these type of problems.

Happy Coding !!

Discussion (0)