C# Multithreaded and Parallel Programming – Book Review

If you are a C# developer who is serious about developing high performance multithreaded applications, then this is the book for you. This book goes in-depth on how to develop multithreaded applications that will take advantage of today’s multicore processors.

Chapter 1 – Explains the history of processors in-depth from single core to multicore. The book also explains, with images, how the (Windows) operating system manages threads on a multicore system.

Chapter 2 – Discusses how to create a simple WPF (Windows Presentation Foundation) application using BackgroundWorker class to demonstrate a non-blocking application.

Chapter 3 & 4 – Discusses Thread class from beginner to advanced such as how to share data between threads to locking, deadlocks, and error handling.

Chapter 5, 6 & 7 – Introduction to Task Parallel Library (TPL). These chapters discusses how to use Parallel class and when to use it instead of the Thread class. The main take away from these chapters (and TPL) is to let .NET handle the thread coordination while the developer focus on the logic of the application.

Chapter 8 – How to take advantage of the tools in Visual Studio to help the developer debug multithreaded application.

Chapter 9 – Introduction to pipeline and producer-consumer design pattern. Discusses how to coordinate efficiently between threads where order matters. For example, thread A reads a frame of video file into a buffer, thread B immediately processes the frame, and thread C writes the frame to file. This process continues until all of the frame has been read from the video file.

Chapter 10 – Introduction of PLINQ. Discusses when and how to use PLINQ to process a LINQ query in parallel.

Chapter 11 – Introduction of async programming. Discusses the newest technique to create non-blocking applications such using async and await.

Overall, great book with examples and images to help the reader understand and apply multithreading features in .NET framework to their application. I highly recommend this book to anyone that wants in-depth practical understanding of multithreaded application in C#.

To findout more about this book, visit the Packt website:
https://www.packtpub.com/application-development/c-multithreaded-and-parallel-programming

Await and async in C#

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="156.618" Width="310.294">
    <Grid>
        <Button Content="Click Here" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="272" Click="Button_Click"/>
        <Label Name="label" Content="Thinking!!!!!!!" HorizontalAlignment="Left" Margin="12,45,0,0" VerticalAlignment="Top" Visibility="Collapsed"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BigInteger factorial(int n)
        {
            BigInteger b = 1;
            for (int i = n; i > 1; i--)
                b *= i;
            return b;
        }

        BigInteger combination(int n, int r)
        {
            BigInteger top = factorial(n);
            BigInteger bottom = factorial(n - r);
            return top / (factorial(r) * bottom);
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        async void clicked()
        {
            await calculate();
        }

        Task calculate()
        {
            return Task.Run(() =>
                {
                    for (int i = 1; i <= 1000; i++)
                    {
                        BigInteger b = combination(1000, i);
                    }

                    Dispatcher.Invoke(() =>
                        {
                            label.Visibility = System.Windows.Visibility.Collapsed;
                        });
                });
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            label.Visibility = System.Windows.Visibility.Visible;
            clicked();
        }
    }
}

Mouseover and press trigger in WPF

MainWindow.xaml

<Window x:Class="ButtonColor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <Style x:Key="ButtonStyle" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid>
                            <Border Name="Border"
                                BorderThickness="2"
                                CornerRadius="3" 
                                BorderBrush="Gray" 
                                Background="{TemplateBinding Background}" />

                            <ContentPresenter 
                                x:Name="contentPresenter"
                                Content="{TemplateBinding Content}" 
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="Border" Property="Background" Value="Magenta"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter TargetName="Border" Property="Background" Value="Yellow" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Content="Click" 
                HorizontalAlignment="Left" 
                Margin="85,80,0,0" 
                VerticalAlignment="Top" 
                Width="215" 
                Height="35"
                Background="Aqua"
                Style="{StaticResource ButtonStyle}" />
    </Grid>
</Window>

More Events in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eventhandler
{
    class myClass
    {
        public string message { get; set; }
    }

    class NormalEvent
    {
        public NormalEvent()
        {
            _show += event1;
            _show += event2;
            _show.Invoke(null, new myClass() { message = "Normal Event Invoked!" });

            Console.WriteLine("\nRemoved event 1");
            _show -= event1;
            _show.Invoke(null, new myClass() { message = "Noraml Event Invoked! After removed!" });
        }

        public event EventHandler<myClass> _show;

        void event1(object sender, myClass e)
        {
            Console.WriteLine("event1");
            Console.WriteLine("Message: " + e.message);
        }

        void event2(object sender, myClass e)
        {
            Console.WriteLine("event2");
            Console.WriteLine("Message: " + e.message);
        }
    }

    class WithLogging
    {
        public WithLogging()
        {
            _show += event1;
            _show += event2;
            events.Invoke(null, new myClass() { message = "With Logging Event Invoked!" });

            Console.WriteLine("\nRemoved event 1");
            _show -= event1;
            events.Invoke(null, new myClass() { message = "With Logging Event Invoked! After removed!" });
        }

        EventHandler<myClass> events;
        public event EventHandler<myClass> _show
        {
            add
            {
                Console.WriteLine("-->adding");
                events += value;
            }

            remove
            {
                Console.WriteLine("-->removing");
                events -= value;
            }
        }

        void event1(object sender, myClass e)
        {
            Console.WriteLine("event1");
            Console.WriteLine("Message: " + e.message);
        }

        void event2(object sender, myClass e)
        {
            Console.WriteLine("event2");
            Console.WriteLine("Message: " + e.message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("--Normal Event--");
            new NormalEvent();
            Console.WriteLine("--Events With Logging--");
            new WithLogging();
        }
    }
}
Posted in C#

Actions and Func in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Actions
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<string, string> name = (fname, lname) => { Console.WriteLine("First Name: " + fname); Console.WriteLine("Last Name: " + lname); };
            name("John", "Smith");
            Console.WriteLine("Using invoke");
            name.Invoke("Jane", "Kate");

            Console.WriteLine();
            Func<string, string, string> fullName = (fname, lname) => { return "First Name: " + fname + " Last Name: " + lname; };
            Console.WriteLine(fullName("Will", "Smith"));
        }
    }
}
Posted in C#

Memory Mapped Files in C#

Program1.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Program1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("MyProgram", 1000))
            {
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryWriter bw = new BinaryWriter(stream);
                    byte [] b = Encoding.ASCII.GetBytes("Hello world!!");
                    foreach (byte oneByte in b)
                    {
                        bw.Write(oneByte);
                    }
                }

                Console.WriteLine("Run program 2 then press any key");
                Console.ReadKey();

                Console.WriteLine("\nProgram 2 said: ");
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryReader sr = new BinaryReader(stream);
                    int c;
                    while ((c = sr.Read()) != 0)
                    {
                        Console.Write((char)c);
                    }
                }
                Console.WriteLine();
            }
        }
    }
}

Program2.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("MyProgram"))
            {
                Console.WriteLine("Program 1 said \n");
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryReader sr = new BinaryReader(stream);
                    int c;
                    while ((c = sr.Read()) != 0)
                    {
                        Console.Write((char)c);
                    }
                    Console.WriteLine();
                }

                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryWriter bw = new BinaryWriter(stream);
                    byte[] b = Encoding.ASCII.GetBytes("Randomly generating code");
                    foreach (byte oneByte in b)
                    {
                        bw.Write(oneByte);
                    }
                }
            }
        }
    }
}
Posted in C#

Extension methods in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExtensionMethods
{
    public static class StringExtension
    {
        public static string capAlternative(this string str)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                if (i % 2 == 0)
                    sb.Append(Char.ToUpper(str[i]));
                else
                    sb.Append(str[i]);
            }
            return sb.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("World of Warcraft".capAlternative());
        }
    }
}
Posted in C#

Dependency Injection Pattern in C# using Unity (part 4)

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace validator
{
    interface IValidator<T>
    {
        bool isValid(T instance);
    }

    class IntegerOnlyValidator : IValidator<string>
    {
        public bool isValid(string instance)
        {
            int i = 0;
            return Int32.TryParse(instance, out i);
        }
    }

    class IntegerOnlyValidatorTest
    {
        [Dependency("validator")]
        public IValidator<string> validator { get; set; }
    }

    class GreaterThanFourValidator : IValidator<int>
    {
        public bool isValid(int instance)
        {
            return instance > 4;
        }
    }

    class GreaterThanFourValidatorTest
    {
        [Dependency("validator")]
        public IValidator<int> validator { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IValidator<string>, IntegerOnlyValidator>("validator");
                IntegerOnlyValidatorTest intOnly = container.Resolve<IntegerOnlyValidatorTest>();
                Console.WriteLine(intOnly.validator.isValid("5554"));
                Console.WriteLine(intOnly.validator.isValid("123ab"));
                
                container.RegisterType<IValidator<int>, GreaterThanFourValidator>("validator");
                GreaterThanFourValidatorTest greater4Only = container.Resolve<GreaterThanFourValidatorTest>();
                Console.WriteLine(greater4Only.validator.isValid(10));
                Console.WriteLine(greater4Only.validator.isValid(1));
            }
        }
    }
}

Dependency Injection via config file
Note: Add reference “System.Configuration”
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="validator"/>
    <namespace name="validator"/>

    <container>
      <register name="integeronly" type="IValidator[string]" mapTo="IntegerOnlyValidator" />
      <register name="greaterthan4" type="IValidator[int]" mapTo="GreaterThanFourValidator" />
      <register type="IntegerOnlyValidatorTest">
        <property name="validator">
          <dependency name="integeronly" />
        </property>
      </register>
      <register type="GreaterThanFourValidatorTest">
        <property name="validator">
          <dependency name="greaterthan4" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace validator
{
    interface IValidator<T>
    {
        bool isValid(T instance);
    }

    class IntegerOnlyValidator : IValidator<string>
    {
        public bool isValid(string instance)
        {
            int i = 0;
            return Int32.TryParse(instance, out i);
        }
    }

    class IntegerOnlyValidatorTest
    {
        [Dependency("validator")]
        public IValidator<string> validator { get; set; }
    }

    class GreaterThanFourValidator : IValidator<int>
    {
        public bool isValid(int instance)
        {
            return instance > 4;
        }
    }

    class GreaterThanFourValidatorTest
    {
        [Dependency("validator")]
        public IValidator<int> validator { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                IntegerOnlyValidatorTest intOnly = container.Resolve<IntegerOnlyValidatorTest>();
                Console.WriteLine(intOnly.validator.isValid("5554"));
                Console.WriteLine(intOnly.validator.isValid("123ab"));

                GreaterThanFourValidatorTest greater4Only = container.Resolve<GreaterThanFourValidatorTest>();
                Console.WriteLine(greater4Only.validator.isValid(10));
                Console.WriteLine(greater4Only.validator.isValid(1));
            }
        }
    }
}

Dependency Injection Pattern in C# using Unity (part 3)

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    interface IConferenceRoom
    {
        IPerson[] People { get; }
    }

    class ConferenceRoom : IConferenceRoom
    {
        IPerson[] people;
        public ConferenceRoom(IPerson[] people)
        {
            this.people = people;
        }

        public IPerson[] People
        {
            get
            {
                return people;
            }
        }
    }

    class Work
    {
        [Dependency("conferenceRoom1")]
        public IConferenceRoom conferenceRoom1 { get; set; }
        [Dependency("conferenceRoom2")]
        public IConferenceRoom conferenceRoom2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IPerson, Person>("John", new InjectionConstructor("John"));
                container.RegisterType<IPerson, Person>("Catherine", new InjectionConstructor("Catherine"));
                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom1",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("John"),
                        new ResolvedParameter<IPerson>("Catherine"))));

                container.RegisterType<IPerson, Person>("Ben", new InjectionConstructor("Ben"));
                container.RegisterType<IPerson, Person>("Elizabeth", new InjectionConstructor("Elizabeth"));
                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom2",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("Ben"),
                        new ResolvedParameter<IPerson>("Elizabeth"))));

                Work w = container.Resolve<Work>();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }

                container.RegisterType<IPerson, Person>("Jennifer", new InjectionConstructor("Jennifer"));
                container.RegisterType<IPerson, Person>("Michael", new InjectionConstructor("Michael"));

                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom_OutofTheBlue",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("Jennifer"),
                        new ResolvedParameter<IPerson>("Michael"))));
                w = container.Resolve<Work>(
                        new PropertyOverride("conferenceRoom2", new ResolvedParameter<IConferenceRoom>("conferenceRoom_OutofTheBlue")));

                Console.WriteLine();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }
            }
        }
    }
}

Dependency Injection via config file
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="work"/>
    <namespace name="work"/>

    <container>
      <register name="John" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="John" />
        </constructor>
      </register>
      <register name="Catherine" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Catherine" />
        </constructor>
      </register>
      <register name="Ben" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Ben" />
        </constructor>
      </register>
      <register name="Elizabeth" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Elizabeth" />
        </constructor>
      </register>
      <register name="Jennifer" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Jennifer" />
        </constructor>
      </register>
      <register name="Michael" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Michael" />
        </constructor>
      </register>
      <register name="conferenceRoom1" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="John"/>
              <dependency name="Catherine"/>
            </array>
          </param>
        </constructor>
      </register>
      <register name="conferenceRoom2" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="Ben"/>
              <dependency name="Elizabeth"/>
            </array>
          </param>
        </constructor>
      </register>
      <register name="conferenceRoom_OutofTheBlue" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="Jennifer"/>
              <dependency name="Michael"/>
            </array>
          </param>
        </constructor>
      </register>
      <register type="Work">
        <property name="conferenceRoom1">
          <dependency name="conferenceRoom1" />
        </property>
        <property name="conferenceRoom2">
          <dependency name="conferenceRoom2" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    interface IConferenceRoom
    {
        IPerson[] People { get; }
    }

    class ConferenceRoom : IConferenceRoom
    {
        IPerson[] people;
        public ConferenceRoom(IPerson[] peopleArg)
        {
            this.people = peopleArg;
        }

        public IPerson[] People
        {
            get
            {
                return people;
            }
        }
    }

    class Work
    {
        [Dependency("conferenceRoom1")]
        public IConferenceRoom conferenceRoom1 { get; set; }
        [Dependency("conferenceRoom2")]
        public IConferenceRoom conferenceRoom2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                Work w = container.Resolve();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }

                w = container.Resolve(new PropertyOverride("conferenceRoom2", 
                    new ResolvedParameter("conferenceRoom_OutofTheBlue")));

                Console.WriteLine();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }
            }
        }
    }
}

Palindrome in C#

Solution to Project Euler problem 4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace problem4
{
    class Program
    {
        static bool isPalindrome(string x)
        {
            int i = 0;
            int j = x.Length - 1;
            while (i <= j)
            {
                if (x[i] != x[j])
                    return false;
                i++;
                j--;
            }

            return true;
        }

        static void Main(string[] args)
        {
            int max = 0;
            for (int i = 100; i < 1000; i++)
            {
                for (int j = 100; j < 1000; j++)
                {
                    int prod = i * j;
                    string prodStr = prod.ToString();
                    if(isPalindrome(prodStr))
                        max = Math.Max(max, prod);
                }
            }
            Console.WriteLine(max);
        }
    }
}