C#

Recommended Build 2014 sessions

build 2014

Finally, I had time to watch Build 2014 sessions. Here are the best I have seen.

Thinking for programmers (Leslie Lamport)

This session is intersection of Computer Science and programming. It will really makes you rethink your approach for solving problems and writing code. One of many interesting thoughts mentioned by Leslie Lamport was a role of specification. It is hard to disagree that in case of very complex code, need for change, after a few months or years, or by other programmer, will cause rewriting code for scratch if we do not have specification. I am recommending this session, because it is not demo of some new Microsoft tool/technology, but a solid piece of knowledge. It is not session for everybody, some may not like it. I love it!

Windows and the Internet of Things (Steve Teixeira)

This session is about writing Software for devices. But not only for PC, tablet or Phone. Also for embedded devices, or customized devices running on Windows Embedded. It is an overview of the future. Not only in Windows World, but at all. Steve Teixeira shows cool demos. E.g. controlling traffic lights using the Phone. He presents Intel Galileo, board which you can get for free by signing up! Only limited number available.

Building Azure Web Sites with Visual Studio Online “Monaco” (Chris Dias)

Visual Studio in Web Browser? I’m in! I am very impressed with progress which is being made in online version of Visual Studio. In addition to simple edits, there is a command line access, intellisense, git integration, side by side file comparison and more.

What’s New for ASP.NET and Web in Visual Studio 2013 Update 2 and Beyond (Scott Hanselman and Scott Hunter)

This is an update of ASP.NET features and future directions. Now, it really starts looking like LEGO pieces. If you are Web Developer, definitely worth to see.

Modern C++: What You Need to Know (Herb Sutter)

This talk is an overview of new features of C++. There is also 10-20 minutes about performance. Recommended if you are not familiar with new C++ features yet. For me, this session could be shorter, and some things could be skipped.

The Future of C# [and VB] (Dustin Campbel and Mads Torgersen)

First part (presented by Dustin Campbel) is about Roslyn. There is demo how custom code diagnostics can be created. Second part (presented by Mads Torgersen) is about new language features. My observation is that they started adding weird things to the language syntax. More over, Mads talk also about Visual Basic (for ~5 mins), which – as he claims – has a future as well. Mads already had similar session on other conferences (dotNetConf, NDC).

Go Mobile with C# and Xamarin (Miguel de Icaza)

Good introduction to Xamarin if you are not familiar with it. There is general overview and philosophy explained. There is also short demo. Good point to get started with Xamarin!

TypeScript (Anders Hejlsberg)

Anders Hejlsberg announced TypeScript 1.0. This session is an overview of TypeScript presented in a very solid way. Timestamped draft notes of the entire talk can be found here.

Developing Neural Networks Using Visual Studio (James McCaffrey)

This session is worth to see at least for first 8 minutes when James is summarizing entire build conference 🙂 The main content is good intro to Neural Networks. It awakened my desire to learn more about Artificial Intelligence and Machine Learning.

I’ve seen also: Building a Large Scale JavaScript Application in TypeScript (only slides, no code…), Building a Single Page Application with ASP.NET and AngularJS (I am not a fan of pasting large chunks of code during demos), Avoiding Cloud Fail: Learning from the Mistakes of Azure with Mark Russinovich (advanced, useful if you use Azure intensively), Building Modern Web Applications with Visual Studio and Web Essentials (just update in new Web Essentials features).


How top 10 programming languages work

TIOBE index: July 2014

I am programming for more than 10 years. I realized that, when I found my first, personal home page (written in PHP) on my hard drive. Some files have last modification date: May 2003. Since that time I was working (or playing) with 9 of top 10 programming language from TIOBE Index list. As I mentioned, I started with PHP, then I learnt a little bit JavaScript (to create fancy menus or ‘secret pages’ on my website). In high school I started learning C++. At the University I learnt C, more C++ and Java. Then I learnt C# on my own, and it is still my favorite language. Along with C# I learnt ASP.NET and T-SQL (to be able to create websites with databases). I also learnt Python and Objective-C. Former became useful when I started my Research Assistant Job.

More experience I gain, more interested I am in how things work underneath the code level. In this post I want to provide short description of the Top 10 programming languages (by TIOBE Index), how they work and their super short history.

PHP

Interpreted language created by Rasmus Lerdorf. Originally, collection of Perl scripts, rewritten to C for performance reasons, ability to work with web-forms and communicate with databases. Most popular interpreter: Zend Engine. Since PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine. Facebook developed two PHP interpreters: HipHop (transforms the PHP scripts into C++ code and then compiles) and HipHop Virtual Machine (converts PHP into a high-level bytecode, which is then translated into x86-64 machine code dynamically). Recommended book: PHP and MySQL Web Development.

JavaScript

Dynamic, interpreted and prototype-based language. JavaScript is superset of ECMAScript standard. Usually used as part of web browser, but also in server-side (Node.js) or even for desktop and mobile application development. Current browsers perform just-in-time compilation. There are many JavaScript engines (interpreters): Rhino (written in Java), SpiderMonkey (written in C, first JS engine), V8 (written C++, by Google, used in Google Chrome), Chakra (performs JIT compilation on a separate CPU core, parallel to the web browser; created by Microsoft, used in Internet Explorer) etc. Recommended book: JavaScript: The Good Parts.

C/C++

C is compiled, static type language created by Denis Ritchie. It influenced many other languages, e.g.: C++, C#, Java, JavaScript, Objective-C, Perl, PHP, Python, and even Unix’s C Shell. C++ is nearly a superset of C, with object oriented features inspired by Simula language, created by Bjarne Stroustrup. C and C++ are compiled to machine specific code, thus platform specific compiler is needed. Most popular compilers: GCC and Visual C++. C++ evolve, Modern C++ (currently C++ 11 and vNext: C++ 14) introduces: smart pointers, for each (range for), lambda functions and much more. Recommended book: Ivor Horton’s Beginning Visual C++ 2012The C Programming Language (by Brian Kernighan and Denis Ritchie)  used to be one of the most popular programming books ever.

Java

C-based language created by James Gosling, which introduces automatic memory management by Garbage Collector. Java is compiled to bytecode (.class files), which runs on JVM (Java Virtual Machine). Its main design goal is “Write Once, Run Anywhere” (WORA). The same code can be compiled to the same bytecode on different machines. Then JVM (platform-specific) translates bytecode to particular machine code during run-time (Just-in-Time (JIT) compilation). Java applets can run in web browser. My personal recommendation for Java book is Hortsmann’s Core Java Volume I – Fundamentals and Volume II – Advanced Features. Well known Java book is Bruce Eckel’s Thinking in Java.

C#

C# is Microsoft’s version of Java language created by Anders Hejlsberg. However, C# is closer to C++ in case of design and syntax. It is compiled to Intermediate Language (equivalent of bytecode in Java) and runs on Common Language Runtime (equivalent of JVM). C# also uses Garbage Collector. It has many features not existing in Java like rich native interoperability, query language (LINQ) or dynamic type. For more, check Comparison of C# and Java. Book for quick start: Sams Teach Yourself Visual C# 2010 in 24 Hours recommended by Eric Lippert (former developer of C# compiler). To dive in, check: C# 5.0 in a Nutshell: The Definitive Reference by Joseph Albahari and Ben Albahari, C# in Depth by Jon Skeet and CLR via C# by Jeffrey Richter.

Python

Dynamic, interpreted language, created by Guido van Rossum. Most popular implementation: CPython (implemented in C). It compiles Python programs to intermediate code (.pyc files) and runs them on Virtual Machine. There are many other implementations, e.g. Jython, which compiles Python to Java Bytecode (.class files). Python is much more expressive language than C or Java. Some constructs, which needs 10 lines of C code or 3 lines of Java code, requires only 1 line in Python (check reverse words example in my post about Python). Python uses whitespace indentation, rather than curly braces or keywords, to delimit blocks. To get started I recommend Google’s Python Class (videos section) created by Nick Parlante. Other resources: Python tutorial and Dive into Python. You can also check my post Python jump start for more details.

Objective-C

Strict superset of C language with object-oriented capabilities inspired by Smalltalk. Every C program can be compiled by Objective-C compiler, C code can be included within Objective-C code. Most popular compilers: Clang and LLVM. Instead of calling methods (like in C++: obj->method(param)), messages to objects are being sent ([obj method:param]) and resolved at runtime (not at compile time like in C++). There is no Garbage Collector (which works at run-time) in Objective-C, but instead Automatic Reference Counting (compile-time feature) is used. Objective-C is the main programming language used by Apple for the OS X and iOS. However, in this year Apple announced plans to replace Objective-C with new Swift language. Resources to learn Objective-C can be found in my other post.

Transact-SQL

Declarative language for managing data held in a relational database management system (RDBMS). Created by Microsoft (for MS SQL Sever), T-SQL is an extension to SQL, which makes it Turing complete. It adds to SQL: procedural programming, local variables, functions for string and date processing, mathematics etc. and allows FROM clause in DELETE and UPDATE statements (which allows joins to be included). T-SQL (and SQL) query differs from program in such a way that they just tell what to do, not how to do that. Figuring out how to execute query is a role of query analyzer. Check Understanding how SQL Server executes a query.  To learn T-SQL, you should learn SQL first. Recommended tutorial: T-SQL Step by Step Course (video tutorial). Recommended books: Itzik Ben-Gan’s Microsoft SQL Server 2012 T-SQL Fundamentals and other his books.

(Visual) Basic (.NET)

Compiled language created by Microsoft. Compiles to native language or P-Code and uses the Microsoft C++ compiler to generate the executable. It derives from BASIC. Similar to Python: tabs and new lines are used to delimit blocks. VB (under Visual Studio) allows to create GUI using drag-and-drop technique. Last version (VB6) was released in 1998 and is abandoned in favor of VB.NET, which introduces many features (present also in C#), but still supported, even on Windows 8. Check Comparison of VB and VB.NET. Both (VB.NET and C#) run on the same run time (CLR). More details can be found here. Recommended tutorials to get started: Visual Basic Fundamentals: Development for Absolute Beginners by Bob Tabor and Visual Basic .NET Tutorials. Good reference is Visual Basic at Wikibooks. To get VB syntax highlighting in SublimeText, this package works.

Summary

I read about all 10 languages in Wikipedia before writing this post. I was surprised how much I could learn in 5-10 minutes reading. I don’t know why, but I feel much better now, when I refreshed and organized my knowledge. If you want to start learning about new programming language, I recommend you to read about it on Wikipedia first. Even more, read about all languages you are using now on Wikipedia as well. It gives you great, high-level overview. Now, Wikipedia will be my start point of research about “some new thing”.


FreeRTOS Jump Start

In this semester I am taking Real-Time Systems course. In one of the programming assignments, we had to develop program for embedded device Tiva C Series LaunchPad TM4C123G. It is a low-cost evaluation platform for ARM Cortex-based microcontrollers from Texas Instruments. It is very nice board if you want to start with embedded devices. It cost only $25 on eBay. You can connect it to your computer using USB. Finally, the board has key feature of embedded device for beginners: the LED.

Tiva LaunchPad

A typical process-control system can be divided into four types of components: the process, sensors, actuators, and controller (see Figure below). LED allows you to mock your target actuator. Majority of operations performed by embedded devices is control of the actuators. What is nice about LED: it is cheap and easy to control whether and how it is working.

safety critical loop

Code Composer Studio

As a development environment for Tiva C Series I recommend you Code Composer Studio. It is Eclipse based IDE, which makes development easy. Especially for beginners. Tutorial for installation and running first program on Tiva TM4C123G board using Code Composer Studio can be found here. I recommend to follow the “Single Download” option (download 1GB+ file). More precisely, download and install: “EK-TM4C123GXL-CCS: TivaWare for C Series and Code Composer Studio for the Tiva C Series TM4C123G LaunchPad” available on this website. I wasted a lot of time trying to install it following “Individual Downloads” instructions (download <1MB file). Installer was hanging, when it was downloading files form the Internet and never recovers. In "Single Download" most of files are already downloaded along with the installer.

FreeRTOS

FreeRTOS is one of the most popular Real Time Operating Systems (RTOS). Additionally, it is free. This is where its name comes from (free + Real Time Operating System = FreeRTOS). The System is written in C language. Thus, we write programs for it in C as well. More details can be found on freertos.org and wikipedia.

The cool thing about FreeRTOS is that it enables easy modifications of Operating System. You can modify e.g. scheduler.

Once you have Code Composer installed. You need to install TivaWare software (which includes FreeRTOS). It can be found in previously downloaded package (if you were following “Single download” option) in TivaWare/SW-EK-TM4C123GXL-1.1.exe.

Running example programs

The TivaWare software contains examples, which are ready to run. You can find them in the directory, where you installed TivaWare C Series software. In my case (default path) it is: C:\ti\TivaWare_C_Series-1.1\examples.

There is an example project freertos_demo. It makes the LED blinking and allows you to manipulate the colors using buttons (located at the bottom of the board). The project can be found in examples\boards\ek-tm4c123gxl\freertos_demo. It is ready to run. You just need to connect the board to the PC, open the project (import it) in Code Composer Studio and run it in debug mode. Code Composer Studio will automatically port the program into the board.

You can modify the code, and make the LED blinking faster or slower. Colors manipulation is also easy.

Queues and semaphores

FreeRTOS supports multitasking. In the Real-Time systems, communication between different tasks are usually implemented using queues and semaphores. It is also the case in freertos_demo program. Buttons send messages to the LED using queues. Semaphores are use to guard concurrent access to UART.

This tutorial is very good point to start with FreeRTOS. It describes basics, queues, semaphores and more.

Summary

Developing code for embedded devices is usually, more complex than for Web or Desktop. Running, even very simple application is more complex, because it requires more steps. You need to configure connection between your computer/OS and specific device. Then you need to setup many settings, which varies almost among every device. The communication with ports is also different and every device has different set of them.

There are no universal installers etc. Every single device require slightly different setup. Sometimes, you need to spend hours to run simple “Hello, World!” application. On the other hand, it is fun to create some system, which do stuff outside of your PC.

If you are interested in embedded devices, check out my other post: BeagleBoard – your personal computer smaller than your wallet.

To get started with FreeRTOS and Tiva C Series: check this tutorial to run first program and FreeRTOS Tutorial to get more details. You can buy Tiva C Series LaunchPad on eBay.


Multithreading: C# vs. Java

In my pervious post I described basic multithreading constructs in C#. Now, I would like to compare them to conforming constructs in Java. It might be useful for those of you, who has already created some multithreaded applications in Java, and would like to learn how to do the same in C#.

Creating a new thread

C#:

using System;
using System.Threading;

class ThreadTest
{
  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();    
  }
 
  static void Method()
  {
    Console.WriteLine("Thread started");
  }
}

Java:

public class Program {
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start(); 
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
    System.out.println("Thread started");
  }
}

Waiting for another thread to finish

C#:

using System;
using System.Threading;

class ThreadTest
{
  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();   
    t.Join(); //wait for thread t
    Console.WriteLine("Created thread finished");
  }
 
  static void Method()
  {
    Console.WriteLine("Started new thread...");
    Thread.Sleep(1000);
    Console.WriteLine("Finishing new thread...");
  }
}

Java:

public class Program {
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start();
    try {
      t.join(); //wait for thread t
      System.out.println("Created thread finished");
	} catch(InterruptedException e) { 
	  // handle exception
	}
    
  }
}
 
class ThreadClass extends Thread  {
  @Override
  public void run() {
    System.out.println("Started new thread...");
    try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      // handle exception
    }
    System.out.println("Finishing new thread...");
  }
}

Accessing shared variable

C#:

using System;
using System.Threading;

class ThreadTest
{
  static readonly object locker = new object();
  static int sharedVariable;

  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();   
    lock(locker)
    {
      // sample operation
      if(sharedVariable==0)
      {
        sharedVariable = 1;
      }
    }
  }
 
  static void Method()
  {
    lock(locker)
    {
      // sample operation
      if(sharedVariable>0)
      {
        sharedVariable++;
      }
    }
  }
}

Java:

public class Program {
  public static int sharedVariable;
  public static final Object lock = new Object();
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start(); 
    synchronized(lock)
    {
      //sample operation
      if(sharedVariable==0) {
        Program.sharedVariable = 1;
      }
    }      
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
    synchronized(Program.lock) {
      //sample operation
      if(Program.sharedVariable>0) {      
        Program.sharedVariable++;
      }
    }
  }
}

Signaling

C#:

using System;
using System.Threading;

class ThreadTest
{
  static EventWaitHandle _waitHandle = new AutoResetEvent (false);
 
  static void Main()
  {
    new Thread (Waiter).Start();    
    Console.WriteLine("Wait for notification...");
    _waitHandle.WaitOne();
    Console.WriteLine("Notification received.");
  }
 
  static void Waiter()
  {
    Thread.Sleep (1000);
    Console.WriteLine("Sending notification...");
    _waitHandle.Set();
  }
}

Java:

class Program
{ 
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start();
    System.out.println("Wait for notification..."); 
    synchronized(t) {
      try {
        t.wait();
      } catch(InterruptedException e) {
        //handle exception
      }
    }
    System.out.println("Notification received.");
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
  	try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      //handle exception
    }    
    System.out.println("Sending notification...");
    synchronized(this) {
      notify();
    }
  }
}

Summary

As we can see, threading constructs in both languages are very similar.

I put all above code in github repository: Threading-in-CSharp-vs-Java.

Do you think, there are some other fundamental examples, which should be mentioned in this post?


Multithreading in C#

Multithreading is one of the advanced topics in Computer Science. Every Developer, sooner or later will need to write some multithreaded application. It is definitely better to do it sooner, even just for exercise, than later.

Everyone who attend a University and got a CS degree had to write at least one concurrent application. Usually, in Java, as ‘standard language for Universities’. At least that was in my case, and two Universities I attended (Wroclaw University of Technology and Kansas State). Many University-based resources from Google are in Java. Sometimes there is C/C++ used. That’s my observation after googling.

As .NET Developer I was interested in multithreading in C#. One of the best sources about that is Threading in C# by Joseph Albahari. It’s an overview of all threading-related features in C#. In this post, I would like to make an overview of the most basic techniques: accessing shared resources and signaling.

Basic locking

The issues with threading are usually correlated with shared resources (e.g. variables). One thread can start modifying it, while in meantime another thread also start do that. Then, sometimes, we cannot predict the final state of the resource (value of variable). Moreover, in one execution it can be value set by thread #1 and in the other – by thread #2.

To solve this issue, we have constructs such as: semaphors or monitors. In C#, the monitor implementation is lock statement. To apply it, we need ‘locker object’, which has to be locked before access to shared resources and unlocked after. Once ‘locker object’ is locked, other threads has to wait until it becomes unlocked. Look at below example (from Albahari’s eBook):

using System;
using System.Threading;

class ThreadTest 
{
  static bool done;    // Static fields are shared between all threads
 
  static void Main()
  {
    new Thread (Go).Start();
    Go();
  }
 
  static void Go()
  {
    if (!done) { done = true; Console.WriteLine ("Done"); }
  }
}

The bool variable done is shared resource. Above program will have 2 threads. First one, starts in a new thread and second one, right after the first one, in main thread. Both will try to access shared resource. We can see that during method Go() execution, the shared variable is accessed actually 2 times. First – to check its value, and second – to set it (if it was false). The problem is that thread #1 can access it first (when it is false), then give up processor for thread #2, which also will check the value (still false) and we will get “Done” printed twice. That’s something we do not want. To solve this issue, we introduce ‘locker object’ represented by variable locker.

using System;
using System.Threading;

class ThreadSafe 
{
  static bool done;
  static readonly object locker = new object();
 
  static void Main()
  {
    new Thread (Go).Start();
    Go();
  }
 
  static void Go()
  {
    lock (locker)
    {
      if (!done) { Console.WriteLine ("Done"); done = true; }
    }
  }
}

Now, the if statement is secured by lock. Every thread, which wants to enter it, has to obtain the lock. Once one thread obtain the lock, another threads cannot. They have to wait, until it becomes unlocked. In above example, when thread #1 has the lock and start executing critical section, then even if it give up for thread #2, we have warranty that another thread will not enter the critical section. Additionally, only thread #1 can release the lock.

The following code:

lock(locker) 
{ 
    //code 
}

is equivalent to (C# 4.0):

bool lockTaken = false;
try
{
  Monitor.Enter (locker, ref lockTaken);
  //code 
}
finally { if (lockTaken) Monitor.Exit (locker); }

Signaling

Another common technique in multithreaded applications is signaling. It is notifying other thread(s). For example: thread #1 can start another thread (thread #2) and wait for signal from it (e.g. that it finished some operation). Thread #2 is performing the operation, while thread #1 is waiting. Once thread #2 finish operation, it notify (send signal) thread #1, which then can continue other computations.

In the example below, then main thread, create new thread to perform Operation. After that it performs some computation and when it is done, it waits for thread #2 to finish its operations. After main thread get notification from thread #2, it can proceed.

using System;
using System.Threading;

class BasicWaitHandle
{
  static EventWaitHandle _waitHandle = new AutoResetEvent (false);
 
  static void Main()
  {
    new Thread (Operation).Start();
    Thread.Sleep (1000);                  // Computation...
    Console.WriteLine ("Wait...");
    _waitHandle.WaitOne();                    // Wait for notification
    Console.WriteLine ("Notified!");
  }
 
  static void Operation()
  {
    Console.WriteLine ("Start operation...");
    Thread.Sleep(2000);               // Computation...
    Console.WriteLine ("Operation finished!");
    _waitHandle.Set();                // Notify the Waiter
    Thread.Sleep(1000);         // Some other computation...
  }
}

Producer-Consumer

The classic multithreaded application is Producer–consumer. Additionally, it is wide used across many real-life applications. In the listing below, there is Producer-Consumer implementation in C# (taken from Threading in C# – part 2):

using System;
using System.Threading;
using System.Collections.Generic;
 
class ProducerConsumerQueue : IDisposable
{
  EventWaitHandle _wh = new AutoResetEvent (false);
  Thread _worker;
  readonly object _locker = new object();
  Queue<string> _tasks = new Queue<string>();
 
  public ProducerConsumerQueue()
  {
    _worker = new Thread (Work);
    _worker.Start();
  }
 
  public void EnqueueTask (string task)
  {
    lock (_locker) _tasks.Enqueue (task);
    _wh.Set();
  }
 
  public void Dispose()
  {
    EnqueueTask (null);     // Signal the consumer to exit.
    _worker.Join();         // Wait for the consumer's thread to finish.
    _wh.Close();            // Release any OS resources.
  }
 
  void Work()
  {
    while (true)
    {
      string task = null;
      lock (_locker)
        if (_tasks.Count > 0)
        {
          task = _tasks.Dequeue();
          if (task == null) return;
        }
      if (task != null)
      {
        Console.WriteLine ("Performing task: " + task);
        Thread.Sleep (1000);  // simulate work...
      }
      else
        _wh.WaitOne();         // No more tasks - wait for a signal
    }
  }
}

class Program
{
	static void Main()
	{
	  using (var q = new ProducerConsumerQueue())
	  {
	    q.EnqueueTask ("Hello");
	    for (int i = 0; i < 10; i++) q.EnqueueTask ("Say " + i);
	    q.EnqueueTask ("Goodbye!");
	  }
	 
	  // Exiting the using statement calls q's Dispose method, which
	  // enqueues a null task and waits until the consumer finishes.
	}
}

It takes advantage of locking and signaling. Producer is creating tasks and putting them into the buffer. Consumer is consuming tasks (fetching them from the buffer). In above program: the buffer is implemented as Queue.

There are two threads:

  • Main thread – creating tasks and adding them into the queue (enqueuing)
  • Work thread – processing tasks (dequeuing)

‘Work thread’ is consuming tasks if the queue is not empty. If the queue is empty, instead of checking its content continuously, it waits for the signal from Main thread. The Main thread notify Work thread every time it enqueued new task into the queue. Work thread terminates, once it receive null task. In above program, it happens when we quit the using statement in Main thread. That cause Dispose() method call (in ProducerConsumerQueue class), which enqueues null task into the queue. During enqueuing and dequeuing, the queue is locked using lock construct.

More detailed description of this implementation can be found on Joe Albahari’s article.

Summary

There are many advantages of multithreading: speeding up applications by performing operations in different thread, while processor is waiting for I/O operation or making UI thread responsive all the time, while processing is done in background. However, multithreaded applications are much harder to find bugs and debug. Because of that: you should avoid multithreading everywhere when possible. Especially, when threads access the shared resource.

To get familiar with multithreading you can read Introduction to Multithreading (with examples in Java) and Multi-threading in .NET: Introduction and suggestions (with “Hello, world” example in C#).

For a jump start you may find useful a session from TechEd New Zealand 2012: Multi-threaded Programming in .NET from the ground up (it’s 2 years old, but still accurate).

To learn more about multithreading in C#, I strongly recommend you Threading in C# by Joseph Albahari, which is also part of C# 5.0 in a Nutshell (book I am reading now…and also recommending!).