Prog in C# – Chapter 1.2

Objective Summary

  • When accessing shared data in a multithreaded environment, you need to synchronize access to avoid errors or corrupted data.
  • Use the lock statement on a private object to synchronize access to a piece of code.
  • You can use the Interlocked class to execute simple atomic operations.
  • You can cancel tasks by using the CancellationTokenSource class with a CancellationToken.

Thought Experiment

Implementing multithreading

You are experiencing deadlocks in your code.  It’s true that you have a lot of locking statements and you are trying to improve your code to avoid the deadlocks.

How can you orchestrate your locking code to avoid deadlocks?

It’s important to make sure that all locking follows the same order when locking multiple objects.  As soon as you start locking dependent objects in different orders, you start getting deadlocks.

Incorrect

How can the Interlocked class help you?

The Interlocked class can help you to execute small, atomic operations without the need for locking.  When you use locking a lot for these kind of operation, you can replace them with the Interlocked statement.

Incorrect

You want to synchronize access by using a lock statement.  On which member do you lock?

Correct
Incorrect

You need to implement cancellation for a long running task.  Which object do you pass to the task?

Correct
Incorrect

You are implementing a state machine in a multithreaded class.  You need to check what the current state is and change it to the new one on each step.  Which method do you use?

Correct
Incorrect