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 Monitor construct

This recipe illustrates another common multithreaded error called a deadlock. Since a deadlock will cause a program to stop working, the first piece in this example is a new Monitor construct that allows us to avoid a deadlock. Then, the previously described lock keyword is used to get a deadlock.

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\Recipe10.

How to do it...

To understand the multithreaded error deadlock, 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;
    using static System.Threading.Thread;
  3. Add the following code snippet below the Main method:
    static void LockTooMuch(object lock1, object lock2)
    {
      lock (lock1)
      {
        Sleep(1000);
        lock (lock2);
      }
    }
  4. Add the following code snippet inside the Main method:
    object lock1 = new object();
    object lock2 = new object();
    
    new Thread(() => LockTooMuch(lock1, lock2)).Start();
    
    lock (lock2)
    {
      Thread.Sleep(1000);
      WriteLine("Monitor.TryEnter allows not to get stuck, returning false after a specified timeout is elapsed");
      if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
      {
        WriteLine("Acquired a protected resource succesfully");
      }
      else
      {
        WriteLine("Timeout acquiring a resource!");
      }
    }
    
    new Thread(() => LockTooMuch(lock1, lock2)).Start();
    
    WriteLine("----------------------------------");
    lock (lock2)
    {
      WriteLine("This will be a deadlock!");
      Sleep(1000);
      lock (lock1)
      {
        WriteLine("Acquired a protected resource succesfully");
      }
    }
  5. Run the program.

How it works...

Let's start with the LockTooMuch method. In this method, we just lock the first object, wait for a second, and then lock the second object. Then, we start this method in another thread and try to lock the second object and then the first object from the main thread.

If we use the lock keyword like in the second part of this demo, there will be a deadlock. The first thread holds a lock on the lock1 object and waits while the lock2 object gets free; the main thread holds a lock on the lock2 object and waits for the lock1 object to become free, which will never happen in this situation.

Actually, the lock keyword is syntactic sugar for the Monitor class usage. If we were to disassemble code with lock, we would see that it turns into the following code snippet:

bool acquiredLock = false;
try
{
  Monitor.Enter(lockObject, ref acquiredLock);

// Code that accesses resources that are protected by the lock.

}
finally
{
  if (acquiredLock)
  {
    Monitor.Exit(lockObject);
  }
}

Therefore, we can use the Monitor class directly; it has the TryEnter method, which accepts a timeout parameter and returns false if this timeout parameter expires before we can acquire the resource protected by lock.

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