A Basic Guide To Unit Testing – Part Three: Mocking Dependencies

The full solution is available on Bitbucket.

So far, we’ve seen how to create and run a very simple unit test. Now we’ll look at how we can unit test a method that requires a dependency without actually testing the dependency.

For this example, I’ve added two more very simple methods to the DiscountCalculator class:

public class DiscountCalculator
    {
        public decimal GetDailyDiscount(decimal listPrice)
        {
            return listPrice - (listPrice * .10m);
        }

        public decimal GetWeekendDiscount(decimal listPrice)
        {
            return listPrice - (listPrice * .15m);
        }

        public decimal GetHolidayDiscount(decimal listPrice)
        {
            return listPrice - (listPrice * .20m);
        }
    }

I’ve also added a couple more unit tests to test those methods:

[TestMethod]
        public void GetWeekendDiscount_GivenListPrice_ReturnsPriceWithFifteenPercentDiscount()
        {
            // Arrange
            decimal listPrice = 33.11m;
            decimal expected = listPrice - (listPrice * .15m);
            var discountCalculator = new DiscountCalculator();

            // Act
            var result = discountCalculator.GetWeekendDiscount(listPrice);

            // Assert
            Assert.AreEqual(expected, result);
        }

        [TestMethod]
        public void GetHolidayDiscount_GivenListPrice_ReturnsPriceWithTwentyPercentDiscount()
        {
            // Arrange
            decimal listPrice = 33.11m;
            decimal expected = listPrice - (listPrice * .20m);
            var discountCalculator = new DiscountCalculator();

            // Act
            var result = discountCalculator.GetHolidayDiscount(listPrice);

            // Assert
            Assert.AreEqual(expected, result);
        }

Now we’re going to add a service that will use the DiscountCalculator…

TDD_AddService

I’m also adding an enum to the project called DiscountType which we will use shortly…

TDD_DiscountEnum

namespace WidgetStore.Services.Enums
{
    public enum DiscountType
    {
        DailyDiscount,
        WeekendDiscount,
        HolidayDiscount
    }
}

In the DiscountService, I’ve created a method with some simple logic that will call one of the DiscountCalculator methods based on the discountType that is passed in as a parameter.

 public class DiscountService
    {
        DiscountCalculator discountCalculator = new DiscountCalculator();

        public decimal GetDiscount(decimal listPrice, DiscountType discountType)
        {
            switch (discountType)
            {
                case DiscountType.WeekendDiscount:
                    return discountCalculator.GetWeekendDiscount(listPrice);
                case DiscountType.HolidayDiscount:
                    return discountCalculator.GetHolidayDiscount(listPrice);
                default:
                    return discountCalculator.GetDailyDiscount(listPrice);
            }
        }
    }

Of special note here is how we are instantiating the DiscountCalculator.

TDD_HardcodedDependency

We have used the new keyword and hardcoded a dependency within our DiscountService object. What this means is that when we create and run a unit test for the GetDiscountMethod, the calls being made to the DiscountCalculator will actually use the that object’s methods, which means we are not just running a test on the GetDiscount method, but on the DiscountCalculator’s methods, too. This means if we get a test failure, we do not know if the failure is being caused by code in the DiscountService.GetDiscount method, or if a method in DiscountCalculator is the culprit.

To fix this we need to set the DiscountService up to use dependency injection so that we can mock the DiscountCalculator and use that mock object rather than testing the real DiscountCalculator. The first thing we need to do is create an interface for the DiscountCalculator. We can either manually create it or right click inside the DiscountCalulator class and select Refactor -> Extract Interface.

TDD_ExtractInterface

Now we have an IDiscountCalculator interface like this…

public interface IDiscountCalculator
    {
        decimal GetDailyDiscount(decimal listPrice);
        decimal GetHolidayDiscount(decimal listPrice);
        decimal GetWeekendDiscount(decimal listPrice);
    }

Now we can modify DiscountService to use dependency injection by adding a constructor that takes a type of IDiscountCalculator as a parameter…

TDD_AddDependencyInjection

In the next part, we’ll create a mock DiscountCalculator and test the GetDiscount method.

A Basic Guide To Unit Testing – Part Two: Writing A Unit Test

The code for this project is at Bitbucket

The next thing we can do with our new unit test is to give it a descriptive name. As was mentioned previously, one helpful function of writing unit tests first is that the tests act as a design guide for writing our code and help us focus only on writing features we need. Thus, even though we may expect to make some changes as we write the test and think more about the design, we should be thinking about a descriptive name that describes exactly what it is that is under test.

There is no concrete rule for naming a unit test, but a generally accepted convention I’ve seen used most often is the one described in Roy Osherove’s The Art Of Unit Testing and consists of three parts…

  1. Unit of work (the name of the method under test)
  2. State under test (what arguments we will pass to the method under test
  3. Expected behavior (what value we expect to be returned from the method)

So, assuming that in our project we want to test a method called “GetDailyDiscount” that takes a listPrice as a parameter and returns the store’s price after calculating the Widget Store’s daily discount of 10%, we might name the test method something like:

    [TestClass]
    public class DiscountCalculatorTests
    {
        [TestMethod]
        public void GetDailyDiscount_GivenListPrice_ReturnsPriceWithTenPercentDiscount()
        {
        }
    }

If we happen to run our unit tests some time in the future and see this test failing, we can see immediately from the title exactly what is being tested and what is the expected result.

Now that we’ve thought about what is being tested and given our test a descriptive name, we can proceed to begin arranging our unit test. We can generally break our test down into three separate parts:

  1. Arrange, where we arrange the objects that will be necessary to conduct our test.
  2. Act, where we will actually run the test against our method under test.
  3. Assert, where we will assert that the result of our test was what we expected.
[TestMethod]
public void GetDailyDiscount_GivenListPrice_ReturnsPriceWithTenPercentDiscount()
{
     // Arrange

     // Act

     // Assert
}

Obviously the comments are optional, however, they help to visualize the different parts of the test.

For the arrange portion, we know that we will need a discount calculator object.

2015-03-23_18-48-14

Not surprisingly, we see a red, squiggly line telling us that this code will not build because the compiler will not be able to resolve the reference for DiscountCalculator. When the project will not build we consider it a test failure, which is exactly what we want to see in TDD (remember, we want to see the test fail before we write code to make it pass). In order to make this pass, we need follow the following steps:

  1. Create a C# class library project named WidgetStore.Services that contains a public DiscountCalculator class.
  2. Add a reference to the service project our unit test project and a using statement in our test file.

TDD_AddServiceProject (1)

Add a using statement to the unit test file and now the DiscountCalculator will resolve…

TDD_UsingServiceHelpers

Thinking back to the name we gave to our unit test, we know that we are going to call a method called GetDailyDiscount and that we will need to pass the list price as a parameter. We will add a variable of type decimal for the list price and initialize it to a value (the value doesn’t matter in this case as long as it is a decimal. Then, in the Act portion of our unit test we can call the method and supply our argument.

TDD_CallGetDailyDiscount

Again, we have an expected failure. We cannot resolve GetDailyDiscount because we have not created it yet. Let’s add the method to the DiscountCalulator to make our test pass. At the moment I’m returning decimal with a return value of 0.00 just to make the test pass for the moment….

TDD_AddGetDailyDiscountMethod

Currently, this test will pass because we have not written our assertion. Let’s add it now. MS Test provides several assertion methods but for the moment we will be using what is probably the most common type of assertion: “AreEqual.”

TDD_AssertionTypes

I’m going to add another variable to the test method called “expected” and initialize it to the value we are expecting to get back. Then in our assertion, we can test whether the result is equal to what we expected…

TDD_GetDailyDiscountAssert

Now we can run our test. If the Test Explorer window is not visible, it can be opened from the top menu by selecting: Test -> Windows -> Test Explorer. Next, we can click run all to build the application and run the test. Shockingly (or not), we will see that the test has failed…

TDD_GetDailyDiscountFail

Looking at the message in the lower window, we see a message informing us that the test failed because we expected a price but actually got back 0.00. We can now fix that by returning to the GetDailyDiscountMethod and implementing some logic that will make the test pass…

TDD_MakeTheTestPass (1)

Now we can run the test again and see that the test passes…

TDD_TestPassed

Congratulations! You’ve written the simplest possible unit test! In part 3, we’ll step it up a bit and look at how to unit test a method that has dependencies by using mocking and dependency injection.

A Basic Guide To Unit Testing – Part One: Setting Up The Test Project

Code for this solution is here.

Test Driven Development (TDD) is a design pattern where we guide the design of our implementation code through the use of tests – more specifically in our case, unit tests. There are several really good reasons for using the test-first approach to software developer, three of the most important being:

  • Test driven development aids the developer in the design process by ensuring the code is written in concise parts that are easily managed and tested.
  • Test driven development helps the developer focus only on features that are really needed in order to pass a given test and leave out unnecessary features – see “You ain’t gonna need it” (YAGNI), and “Keep It Simple, Stupid” (KISS).
  • Writing tests first allows the developer to see that the test fails until the implementation code is written, therefore proving that the implementation code is actually causing the test to pass (more on this later).

An important concept to keep in mind when writing unit tests is that a test should only test one particular method and should not test dependencies such as a databases or other objects. Later, we’ll delve into using a mocking framework and using dependency injection, but for the first example we’ll get an overview of TDD by creating a very simple method that does not rely on any dependencies.

We’re going to imagine that a widget store has asked us to create a new service that will calculate different types of discounts. The store can supply the list price and type of discount to the service, and the service will return the price of the item with the discount applied. Note: please remember that the purpose of the code in this example is not to consider the best real-life way to write a such a service, but simply to create some basic code and dependencies to demonstrate unit testing.

We will start by creating a blank solution and naming it WidgetStore…

TDD_001

Next we’ll right click the blank solution in the solution explorer and add a new project…

TDD_002

Create a unit test project called WidgetStore.Tests…

2015-03-22_13-54-27

Delete the UnitTest1.cs file visual studio created. Next, create a folder in the project called ServiceHelpers. The first tests in this example will be testing a discount calculator class which will reside in a folder called ServiceHelpers in our service project which will eventually be used by the service to calculate discounts. Keeping a folder structure in our test project that mirrors the folder structure that appears in the projects being tested helps to keep thing organized.

2015-03-22_13-58-11

Visual Studio names the new unit test file UnitTest1.cs by default.

2015-03-22_14-04-20

We’ll right click that file and rename it to DiscountCalculatorTests…

2015-03-22_14-12-37

2015-03-22_14-10-41

In part 2, we’ll talk about naming conventions for unit tests and start writing test code…

WCF Dependency Injection

You can view all of the code for this solution here: Wcf Dependency Injection Example

Dependency injection in Wcf services is complicated by the fact that, out of the box, Wcf requires a parameterless constructor. We could just add one constructor for dependency injection while running unit tests and another parametless constructor for Wcf at runtime like this…

     public class DiscountService : IDiscountService
    {
        IDiscountCalculator discountCalculator;

        // A parameterless constructor so Wcf can resolve 
        // dependency at runtime.
        public DiscountService()
        {
            discountCalculator = new DiscountCalculator();
        }


        // A constructor where unit tests can inject a dependency
        public DiscountService(IDiscountCalculator discountCalculator)
        {
            this.discountCalculator = discountCalculator;
        }

        public decimal GetDiscount(decimal listPrice, DiscountTypes discountType)
        {
            // Service logic using the discountCalculator logic
            switch (discountType)
            {
                case DiscountTypes.WeekendDiscount:
                    return discountCalculator.GetPriceWithWeekendDiscount(listPrice);
                case DiscountTypes.HolidayDiscount:
                    return discountCalculator.GetPriceWithHolidayDiscount(listPrice);
                default:
                    return discountCalculator.GetPriceWithDailyDiscount(listPrice);
            }
        }

However, while this will actually work in practice, we have strayed from our dependency injection pattern at runtime. In order to implement dependency injection, we will need to make sure the Inversion of Control container is set up correctly (Unity in this example), and create a service host factory using code similar to the following…

The service host…

    public class UnityServiceHost : ServiceHost
    {
        public UnityServiceHost(IUnityContainer container, Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            foreach (var cd in this.ImplementedContracts.Values)
            {
                cd.ContractBehaviors.Add(new UnityInstanceProvider(container));
            }
        }
    }

The UnityInstanceProvider that resolves the service type…

    public class UnityInstanceProvider : IInstanceProvider, IContractBehavior
    {
        private readonly IUnityContainer container;

        public UnityInstanceProvider(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            this.container = container;
        }


        public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
        {
            return this.GetInstance(instanceContext);
        }

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
        {
            return this.container.Resolve(
      instanceContext.Host.Description.ServiceType);

        }

        public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
        {
        }

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.InstanceProvider = this;
        }

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }
    }

And the service host factory…

    public class UnityServiceHostFactory : ServiceHostFactory
    {
        private readonly IUnityContainer container;

        public UnityServiceHostFactory()
        {
            container = new UnityContainer();
            RegisterTypes(container);
        }

        protected override ServiceHost CreateServiceHost(
          Type serviceType, Uri[] baseAddresses)
        {
            return new UnityServiceHost(this.container,
              serviceType, baseAddresses);
        }

        // This is where we register are types so Unity can resolve them
        // at runtime.
        private void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType<ICalculationEngine, CalculationEngine>();
        }

    }

In addition, we need to make sure the service is configured to use the service host factory by right clicking the .svc file, going to “View Markup” and changing it similar to this…

<%@ ServiceHost Language="C#" Debug="true" Service="WcfDiscountService.WcfDiscountService" Factory="WcfDiscountService.UnityServiceHostFactory" %>

With these classes in place, we can use runtime dependency injection with Wcf services.

Dynamic Vs Var

The dynamic language runtime is a library that runs on the Common Language Runtime (CLR) and provides a dynamic type system. This allows types to be bound at runtime rather than at compile time.

The difference between dynamic and var is that var is bound at compile time, so…
var X = new X();
is inferred at compile time to mean…
X x = new X();

With the dynamic keyword, this binding does not occur until execution time.

C# – Create and use objects at runtime with Activator

Activator

The activator class uses reflection to dynamically create and use instances of objects at runtime. Example:

//Demonstrate Activator class

using System;
using System.Reflection;

namespace Activator_Test
{
    public class Program
    {
        //Create and interface with a simple method
        public interface IPerson
        {
            void SayHi();
        }

        //Create a class to implement the interface
        public class Person : IPerson
        {
            public string Name { get; set; }
            public int Age { get; set; }

            //Note this contructor takes 2 arguments
            public Person(string name, int age)
            {
                this.Name = name;
                this.Age = age;
            }

            //Public method that we can use Activator to call
            public void SayHi()
            {
                Console.WriteLine("Hi, my name is {0} and I'm {1}.", this.Name, this.Age);
            }
        }

        static void Main(string[] args)
        {
            //Loop through the types in the assembly that is currently executing
            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                //If there is a type of IPerson in the executing assembly...
                if (type.GetInterface("IPerson") != null)
                {
                    //Create an instance of type IPerson using Activator.CreateInstance()
                    //The overloaded CreateInstance method takes the type we are creating
                    //and the arguments for the constructor. 
                    //If there are overloaded contructors for the type, the closest matching 
                    //constructor for the arguments we are supplying will be used. 
                    IPerson person = Activator.CreateInstance(type, "Dave", 30) as IPerson;
                    person.SayHi(); //Call a method on the object we created with Activator
                }
            }
        }
    }
}

Activator_001

C# Reflection

Reflection

Reflection allows you to use an object’s metadata to learn what the members of an object are and use them in your code.  The first step is to invoke the static GetType() method which is inherited by all objects from the Object base class. Once you the have the type, you can use reflection to access the object’s members. In this first example, we look at the object’s properties:

//Demonstrate reflection
using System;

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person("Dave", 30);

            Console.WriteLine(person.ToString());

            Person.CalculateDogYears(30);

            person.LieAboutAge();

            Console.WriteLine(person.ToString());

            Console.WriteLine();

            Console.WriteLine("****Use Reflection to view properties***");
            var type = typeof(Person);
            var members = type.GetProperties();

            foreach (var memberInfo in members)
            {
                Console.WriteLine(memberInfo.Name);
            }

            Console.WriteLine();
        }
    }

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }

        public static void CalculateDogYears(int age)
        {
            //This calculation is not accurate by hey, it's just an example!
            Console.WriteLine("Your age in dog years is " + (age * 7));
        }

        public void LieAboutAge()
        {
            TakeAYearOffAge();
        }

        private void TakeAYearOffAge()
        {
            this.Age = Age - 1;
        }

        public override string ToString()
        {
            return "Yo I'm " + this.Name + " and I'm " + this.Age + " years old!";
        }
    }
}

Reflection_001

We can also view the methods:

           Console.WriteLine("****Use Reflection to view methods***");
            var type = typeof(Person);
            var members = type.GetMethods();

            foreach (var memberInfo in members)
            {
                Console.WriteLine(memberInfo.Name);
            }

 

Reflection_0021

 

Or we can specify which members to view using binding flags:

           Console.WriteLine("****Use Reflection to view static members***");
            var type = typeof(Person);
            var members = type.GetMembers(
                BindingFlags.Public |
                BindingFlags.Static
                );

            foreach (var memberInfo in members)
            {
                Console.WriteLine(memberInfo.Name);
            }

Reflection_0031

 

            Console.WriteLine("****Use Reflection to view members***");
            var type = typeof(Person);
            var members = type.GetMembers(
                BindingFlags.Public |
                BindingFlags.Static |
                BindingFlags.NonPublic | 
                BindingFlags.Instance
                );

            foreach (var memberInfo in members)
            {
                Console.WriteLine(memberInfo.Name);
            }

 

 

Reflection_0042

 

Use reflection to get data annotations for properties. First, add data annotations to Person class (this requires you to add using System.ComponentModel.DataAnnotations):

    class Person
    {
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        public int Age { get; set; }
//...

Then, get property info and attributes:

            
           Console.WriteLine("****Use Reflection to view attributes for Name property***");
            var type = typeof(Person);
            PropertyInfo propertyInfo = type.GetProperty("Name");
            object[] attributes = propertyInfo.GetCustomAttributes(false);

            foreach (var attribute in attributes)
            {
                Console.WriteLine(attribute.GetType().Name);
            }

Reflection_005

C# Threads

Threads are where units of code are executed, and multiple threads can run at the same time on a multicore processor or across multiple processors. On a single core processor, the execution of multiple threads can be simulated (this is known as preemptive scheduling). The operating system kernel schedules thread execution. Threads can be boosted based on priority or blocked when a higher priority thread is using needed resources.

Use of threads is complex and can lead to bugs, especially race conditions. Race conditions occur when multiple threads attempt to modify the same data in an unexpected sequence. For example, Thread1 reads int x and performs a calculation, but before assigning the result back to x, Thread2 reads x, performs a calculation and assigns its value to x. This can cause unpredictable values assigned to variables during the programs execution.

Another bug that can result from improper thread use is deadlocks. A deadlock occurs when two threads lock two variables, then try to access the variable already locked by the other thread. When this occurs, each thread stops and waits indefinitely for the variable they are trying to access to be released.

Example of starting a worker thread:

using System;
using System.Threading;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a worker thread
            var worker = new Thread(() =&gt;
                {
                    Thread.Sleep(5000);
                    Console.WriteLine("I'm a worker thread doin' some work!");
                });

            //Main thread outputs message to console, then starts worker thread.
            Console.WriteLine("I'm the main thread, starting up a worker thread...");
            worker.Start();

            Console.WriteLine("Main thread started the worker thread");

            //Make main thread sleep, then output message while worker runs in background
            Thread.Sleep(2000);
            Console.WriteLine("Press ENTER to quit when worker finishes...");
            Console.ReadLine();
        }
    }
}

Threads_001-624x315

 How to stop a thread

You should never use the Abort method to stop a thread. Using the Abort method could stop the thread at any unknown point possibly causing corrupt data and throwing a ThreadAbortExcepiton. This is called an asynchronous exception because it can occur at any point in the thread. Likewise, the Suspend and Resume methods are deprecated because the code calling the Suspend method will not know at what point during the threads execution it is calling for the suspension. The best way to end a thread’s execution is to set a flag and allow it to end naturally. Example:

using System;
using System.Threading;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            var stop = false;

            //create a worker thread
            var worker = new Thread(() =&gt;
                {
                    while (!stop)
                    {
                        Console.WriteLine("I am Sam.");
                        Thread.Sleep(2000);
                        Console.WriteLine("Sam I am.");
                        Thread.Sleep(2000);
                    }
                });

            //Main thread outputs message to console, then starts worker thread.
            Console.WriteLine("I'm the main thread, starting up the annoying worker thread...");
            worker.Start();

            Console.WriteLine("Press ENTER when you've had enough...");
            Console.ReadLine();

            //set stop flag to true
            stop = true;
            //Join() causes the current thread to wait for the worker thread to stop before continuing execution. 
            worker.Join();

            Console.WriteLine("Worker stopped. Press enter to quit.");
            Console.ReadLine();
        }
    }
}

Threads_002

Thread Locking

The lock keyword locks a thread so that other threads are blocked from executing on a unit of code until the locked thread has complete its execution. A dummy object is typically used as a cookie to perform the synchronization.

//Demonstrate a race condition

using System;
using System.Threading;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            //for this program, we want the account balance to remain 1000
            decimal accountBalance = 1000M;
            decimal rent = 800M;
            decimal carPayment = 200M;
            decimal salary = 1000M;

            //a worker thread to demonstrate a race condition
            var payBills = new Thread(() =&gt;
                {
                    //Execute the loop many times to demonstrate errors
                    for (int i = 0; i &lt; 1000000; i++)
                    {
                            accountBalance -= rent;
                            accountBalance -= carPayment;
                    }
                });

            payBills.Start();

            //We add 1000 to the account balance for everytime we subtract 1000.
            //So we expect the balance to be the same when the program ends. 
            //However, we will be in for a surprise...
            for (int i = 0; i &lt; 1000000; i++)
            {
                accountBalance += salary;
            }

            payBills.Join();

            Console.WriteLine(accountBalance);
        }
    }
}

It seems that we are adding the same amount to the account balance as we subtracted and therefore the ending balance should be the same as what we started with. But instead we get different answers every time we run the program, and most likely not the answer we expected:

RaceConditions_001

 

Let’s try that again…

RaceConditions_002

One more time…

RaceConditions_003

 

So what’s going on?

RaceConditionsSlide_001-2

RaceConditionsSlide_002

 

The two separate threads each create a variable i on the heap. These variables are closures, meaning they each operate in their own isolated environments. This means the reading, computation, and writing of the variables is going on independently of one another, and obviously not in any predictable order.

To solve this, we need to lock the threads so that when one thread is operating on the account balance, the other thread is locked until execution is finished.

//Demonstrate a race condition

using System;
using System.Threading;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            //create an object to use as a lock
            object threadLock = new object();

            //for this program, we want the account balance to remain 1000
            decimal accountBalance = 1000M;
            decimal rent = 800M;
            decimal carPayment = 200M;
            decimal salary = 1000M;

            //a worker thread to demonstrate a race condition
            var payBills = new Thread(() =&gt;
                {
                    //Execute the loop many times to demonstrate errors
                    for (int i = 0; i &lt; 1000000; i++)
                    {
                        lock (threadLock)
                        {
                            accountBalance -= rent;
                            accountBalance -= carPayment;
                        }
                    }
                });

            payBills.Start();

            //We add 1000 to the account balance for everytime we subtract 1000.
            //So we expect the balance to be the same when the program ends. 
            //However, we will be in for a surprise...
            for (int i = 0; i &lt; 1000000; i++)
            {
                lock(threadLock)
                accountBalance += salary;
            }

            payBills.Join();

            Console.WriteLine("Account balance: " + accountBalance);
        }
    }
}

Now when we run the program we get the expected result…
RaceConditions_004

Mutexes

Mutexes work similar to locking. Using a lock is a high-level CLR operation, whereas mutexes at a much lower level with operating system. Because of this, mutexes run much slower, but they are also better suited for synchronizing parts of large system because they exist at the operating system level.

//Demonstrate mutexes

using System;
using System.Threading;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a mutex
            var mutex = new Mutex();

            //for this program, we want the account balance to remain 1000
            decimal accountBalance = 1000M;
            decimal rent = 800M;
            decimal carPayment = 200M;
            decimal salary = 1000M;

            //a worker thread to demonstrate a race condition
            var payBills = new Thread(() =&gt;
                {
                    Console.WriteLine("This takes a while...");
                    //Execute the loop many times to demonstrate errors
                    for (int i = 0; i &lt; 1000000; i++)
                    {
                        mutex.WaitOne();
                            accountBalance -= rent;
                            accountBalance -= carPayment;
                            mutex.ReleaseMutex();
                    }
                });

            payBills.Start();

            //We add 1000 to the account balance for everytime we subtract 1000.
            //So we expect the balance to be the same when the program ends. 
            //However, we will be in for a surprise...
            for (int i = 0; i &lt; 1000000; i++)
            {
                mutex.WaitOne();
                accountBalance += salary;
                mutex.ReleaseMutex();
            }

            payBills.Join();

            Console.WriteLine("Account balance: " + accountBalance);
        }
    }
}

Mutexes

Task Parallel Library

As of .Net 4, threads should be handled with the Task Parallel Library (TPL). Example:

//Demonstrate Task Parallel Library

using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace Threads_001
{
    class Program
    {
        static void Main(string[] args)
        {
            DownloadAsynchronously();

            Console.WriteLine("Thread {0} completed.", Thread.CurrentThread.ManagedThreadId);
        }

        public static void DownloadAsynchronously()
        {
            string[] urls =
            {
                "http://www.huffingtonpost.com",
                "http://www.nyt.com",
                "http://www.cnn.com",
                "http://www.latimes.com",
                "http://www.washingtonpost.com",
                "http://www.denverpost.com",
            };

            Parallel.ForEach(urls, url =&gt;
            {
                var client = new WebClient();
                var htm = client.DownloadString(url.ToString());
                Console.WriteLine("Download {0} chars from {1} on thread {2}",
                    htm.Length, url, Thread.CurrentThread.ManagedThreadId);
            });
        }
    }
}

ParallelRequests

How To Compile And Run A C# Program From The Command Line

Knowing how to compile your program from the command line is a good skill for any programmer to know. Here’s how to do it…

Type code into a text editor like Notepad and save as hello.cs:

using System;

class Program{
	static void Main()
	{
		Console.Write("Hello world!");
	}
}

Open command prompt by going to Windows Start and typing ‘cmd’ in the search box. Then click enter.

Change directory to where you saved the hello.cs file:

CommandCS_001-624x315

 

Run the compiler by typing its complete path followed by the file name (hello.cs):

CommandCS_002-624x315

 

You now have a hello.exe file in the same directory as your hello.cs file. From the directory where hello.exe is located, run the program by typing its name – ‘hello’.

CommandCS_003-624x315

 

C# Delegates Simplified

Delegates in C# are references to methods that can be passed as arguments to other methods. This allows you to decide at runtime which method to call from among a series of methods with the same signature.

When declaring a delegate you specify the signature of the methods that the delegate may reference:

public delegate void someMethod();

Example of using a delegate:

class MagicUser
{
//declare a delegate that takes a Random object as an argument and returns an int
public delegate int CastSpell(Random rand);

//create a Random object called rand that we can pass to the delegate
private Random rand = new Random();

//create a method that takes a CastSpell delegate as an argument
public void CheckDamage(CastSpell spellDelegate)
{
//create a variable and call the delegate that was passed as an argument
int damage = spellDelegate(rand);

//use the result
Console.WriteLine("The magic user's spell did {0} points of damage", damage);
}

 

class Fireball
    {
        //create a method that can be referenced by the delegate
        public int CastFireball(Random rand)
        {
            Console.WriteLine("BOOM!!");
            return rand.Next(1, 5);
        }
    }

 

class LightningBolt
    {
        //create a method that can be referenced by the delegate
        public int CastLightningBolt(Random rand)
        {
            Console.WriteLine("Lightning bolt!!");

            return rand.Next(1, 10);
        }
    }

 

class Program
    {
        static void Main(string[] args)
        {
            //create the needed objects
            var merlin = new MagicUser();
            var fireball = new Fireball();
            var lightningbolt = new LightningBolt();

            //create references to the delegates
            var fireballDelegate = new MagicUser.CastSpell(fireball.CastFireball);
            var lightningboltDelegate = new MagicUser.CastSpell(lightningbolt.CastLightningBolt);

            //call CheckDamage using each delegate
            merlin.CheckDamage(fireballDelegate);
            merlin.CheckDamage(lightningboltDelegate);
        }
    }

 

Delegates