Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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 in C# 5.0 Cookbook

You're reading from   Multithreading in C# 5.0 Cookbook Multithreaded programming can seem overwhelming but this book clarifies everything through its cookbook approach. Packed with practical tasks, it's the quick and easy way to start delving deep into the power of multithreading in C#.

Arrow left icon
Product type Paperback
Published in Nov 2013
Publisher Packt
ISBN-13 9781849697644
Length 268 pages
Edition 1st 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 Task Parallel Library 5. Using C# 5.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 if 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 2012. 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 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  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:
    Console.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();
    
    Console.WriteLine("Total count: {0}",c.Count);
    Console.WriteLine("--------------------------");
    Console.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();
    Console.WriteLine("Total count: {0}", c1.Count);
  5. Run the program.

How it works...

When the main program starts, it first creates an object of the class Counter. 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 zero, 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 happens, 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 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 must 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 be waiting in a blocked state until it is unlocked. This could be a serious performance issue and later, in Chapter 2, Thread Synchronization, we will learn more about this.

You have been reading a chapter from
Multithreading in C# 5.0 Cookbook
Published in: Nov 2013
Publisher: Packt
ISBN-13: 9781849697644
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
Banner background image