Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Multithreading with C# Cookbook, Second Edition

You're reading from   Multithreading with C# Cookbook, Second Edition Quick answers to common problems

Arrow left icon
Product type Paperback
Published in Apr 2016
Publisher
ISBN-13 9781785881251
Length 264 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Evgenii Agafonov Evgenii Agafonov
Author Profile Icon Evgenii Agafonov
Evgenii Agafonov
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Threading Basics FREE CHAPTER 2. Thread Synchronization 3. Using a Thread Pool 4. Using the Task Parallel Library 5. Using C# 6.0 6. Using Concurrent Collections 7. Using PLINQ 8. Reactive Extensions 9. Using Asynchronous I/O 10. Parallel Programming Patterns 11. There's More Index

Locking with a C# lock keyword

This recipe will describe how to ensure that when one thread uses some resource, another does not simultaneously use it. We will see why this is needed and what the thread safety concept is all about.

Getting ready

To work through this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe9.

How to do it...

To understand how to use the C# lock keyword, perform the following steps:

  1. Start Visual Studio 2015. Create a new C# console application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
    using static System.Console;
  3. Add the following code snippet below the Main method:
    static void TestCounter(CounterBase c)
    {
      for (int i = 0; i < 100000; i++)
      {
        c.Increment();
        c.Decrement();
      }
    }
    
    class Counter : CounterBase
    {
      public int Count { get; private set; }
    
      public override void Increment()
      {
        Count++;
      }
    
      public override void Decrement()
      {
        Count--;
      }
    }
    
    class CounterWithLock : CounterBase
    {
      private readonly object _syncRoot = new Object();
    
      public int Count { get; private set; }
    
      public override void Increment()
      {
        lock (_syncRoot)
        {
          Count++;
        }
      }
    
      public override void Decrement()
      {
        lock (_syncRoot)
        {
          Count--;
        }
      }
    }
    
    abstract class CounterBase
    {
      public abstract void Increment();
    
      public abstract void Decrement();
    }
  4. Add the following code snippet inside the Main method:
    WriteLine("Incorrect counter");
    
    var c = new Counter();
    
    var t1 = new Thread(() => TestCounter(c));
    var t2 = new Thread(() => TestCounter(c));
    var t3 = new Thread(() => TestCounter(c));
    t1.Start();
    t2.Start();
    t3.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    
    WriteLine($"Total count: {c.Count}");
    WriteLine("--------------------------");
    
    WriteLine("Correct counter");
    
    var c1 = new CounterWithLock();
    
    t1 = new Thread(() => TestCounter(c1));
    t2 = new Thread(() => TestCounter(c1));
    t3 = new Thread(() => TestCounter(c1));
    t1.Start();
    t2.Start();
    t3.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    WriteLine($"Total count: {c1.Count}");
  5. Run the program.

How it works...

When the main program starts, it first creates an object of the Counter class. This class defines a simple counter that can be incremented and decremented. Then, we start three threads that share the same counter instance and perform an increment and decrement in a cycle. This leads to nondeterministic results. If we run the program several times, it will print out several different counter values. It could be 0, but mostly won't be.

This happens because the Counter class is not thread-safe. When several threads access the counter at the same time, the first thread gets the counter value 10 and increments it to 11. Then, a second thread gets the value 11 and increments it to 12. The first thread gets the counter value 12, but before a decrement takes place, a second thread gets the counter value 12 as well. Then, the first thread decrements 12 to 11 and saves it into the counter, and the second thread simultaneously does the same. As a result, we have two increments and only one decrement, which is obviously not right. This kind of a situation is called a race condition and is a very common cause of errors in a multithreaded environment.

To make sure that this does not happen, we must ensure that while one thread works with the counter, all other threads wait until the first one finishes the work. We can use the lock keyword to achieve this kind of behavior. If we lock an object, all the other threads that require an access to this object will wait in a blocked state until it is unlocked. This could be a serious performance issue and later, in Chapter 2, Thread Synchronization, you will learn more about this.

You have been reading a chapter from
Multithreading with C# Cookbook, Second Edition - Second Edition
Published in: Apr 2016
Publisher:
ISBN-13: 9781785881251
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime