Pages

Wednesday, December 18, 2013

C# Multithreading Loop with Parallel.For or Parallel.ForEach

Loop is such a trivial and so frequently used thing. And sometimes loops just killing performance of the whole application. I want the loop perform faster, but what can I do?

Starting from .NET Framework 4 we can run loops in parallel mode using Parallel.For method instead of regular for or Parallel.ForEach instead of regular foreach. And the most beautiful thing is that .NET Framework automatically manages the threads that service the loop!

But don't expect to receive performance boost each time you replace your for loop with Parallel.For, especially if your loop is relatively simple and short. And keep in mind that results will not come in proper order because of parallelism.

Now let's see the code. Here is our regular loop:
for (int i = 1; i < 1000; i++)
{
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);
}
And here is how we write it with Parallel.For:
Parallel.For(1, 1000, (i) =>
{
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);
});

Sunday, December 1, 2013

WPF MultiBinding Example (MultiValueConverter)

As you probably know the main key of WPF is binding. We bind WPF control to a property and data flows from business logic to UI and vice versa. But what if we need to bind several properties to a single control and depending on the state of these properties we will decide what to display? This technique called MultiBinding.
MultiBinding in WPF is always accompanied with MultiValueConverter. Inside it we define the logic that will decide what value to pass to our WPF control.

Today I'll show a simple example of MultiBinding in WPF. In my sample application I have three TextBox controls and a single TextBlock. I want to achieve this scenario: I want to show the text in the TextBlock, but only if each of three TextBoxes contain some text.

WPF MultiBinding Sample Application

Wednesday, November 27, 2013

MEF Simple Application in C#

I believe the best way to learn something new is to learn by simple and easy to understand example. Once you got the principles you can always proceed to more complex stuff. So today I'll show a simple example of MEF that will give you the basics.

Managed Extensibility Framework (MEF) is a component of .NET 4 and it allows to developer to build extensible applications. Imagine situation when you have some application and you know that in the future you will want to add more features to it, but you don't know exactly what and when they will be added, or may be you want another developer to develop new feature and integrate it seamlessly into the main application. So it looks like we need some module structured application here, right? And this is exactly what MEF provides.
Now to our sample application. When user starts it he asked to enter a string and a command (name of operation) he want to apply on that string. Once it's done the program will print the result string. So every operation we want to be a separate module. Enough bla bla! Let's see the code! :)

First, the Core class which is a part of the main application. Core class concentrates and launches all available extensions:
public interface ICore
{
    String PerformOperations(string data, string command);
}

[Export(typeof(ICore))]
public class Core : ICore
{
    [ImportMany]
    private IEnumerable<Lazy<IOperation, IOperationCommand>> _operations;

    public string PerformOperations(string data, string command)
    {
        foreach (Lazy<IOperation, IOperationCommand> i in _operations)
        {
            if (i.Metadata.Command.Equals(command))
                return i.Value.Operate(data);
        }
        return "Unrecognized operation";
    }
}

Saturday, July 27, 2013

Communication Between Views in MVVM (Pub-Sub Pattern)


When you write WPF application you obviously use MVVM pattern. At some point you probably will need some communication between separated views. Well, there is a bunch of tools for this purposes -MVVM Light’s Messenger or Microsoft Prism’s EventAggregator, but today I'll show an alternative way by using Publish-Subscribe Pattern aka Observer.

Pub-Sub is a simple static class that will make your life easier with MVVM:
public delegate void PubSubEventHandler<T>(object sender, PubSubEventArgs<T> args);

public class PubSubEventArgs<T> : EventArgs
{
    public T Item { get; set; }

    public PubSubEventArgs(T item)
    {
        Item = item;
    }
}

public static class PubSub<T>
{
    private static Dictionary<string, PubSubEventHandler<T>> events = 
            new Dictionary<string, PubSubEventHandler<T>>();

    public static void AddEvent(string name, PubSubEventHandler<T> handler)
    {
        if (!events.ContainsKey(name))
            events.Add(name, handler);
    }
    public static void RaiseEvent(string name, object sender, PubSubEventArgs<T> args)
    {
        if (events.ContainsKey(name) && events[name] != null)
            events[name](sender, args);
    }
    public static void RegisterEvent(string name, PubSubEventHandler<T> handler)
    {
        if (events.ContainsKey(name))
            events[name] += handler;
    }
}

Friday, April 19, 2013

Singleton Design Pattern C# Example

Singleton is one of the most frequently used Design Patterns in Software Engineering. You should apply Singleton pattern if you want to ensure that your class will have only one instance with a global point of access to it.

Let's look at Singleton code:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton GetInstance
   {
      get 
      {
         return instance; 
      }
   }
}
As you can see the code is pretty simple. Class is defined as sealed in order to prevent derivation. Also Singleton variable is marked readonly, which means that it can be assigned only during static initialization or in a constructor.
This approach has only one downside - it's not thread safe. This code must be improved if you work in multithreaded environment.

Saturday, April 6, 2013

Factory Design Pattern C# Example

Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes.

Let's see Factory Pattern in action on a simple example. Assume you have two different classes Toyota and Suzuki, they both implements abstract class Car. You need to instantiate one of these classes, but you don't know which of them, it depends on user. This is perfect scenario for the Factory Pattern.

Factory Design Pattern example program diagram

Sunday, March 31, 2013

Managing Dependency Injection in C# with Autofac


Dependency Injection in software engineering is a specific form of inversion of control. Conventionally, when an object needs access to a particular service, this object takes responsibility for access to this service.

Commonly, an object receives a link to the service location or appeals to some "service locator" and requests a reference to the implementation of a specific type of service. When implementing Dependency Injection, object simply provides a property that is able to keep a reference to the type of service, and when the object is created, a reference to the implementation of the desired type of service is automatically inserted into the property (field).

Dependency Injection is more flexible because it becomes easier to create alternative implementations of this type of service, and then specify exactly which implementation should be used, for example in the configuration file, with no changes in the objects that use this service. This is especially useful in unit testing.

C# Dependency Injection with Autofac

Today I'll show a simple example of managing dependency injection with Autofac. Autofac is an Inversion of Control Container for .NET. It helps to manage dependencies between classes so that applications stay easy to change as they grow in size and complexity. This achieved by treating regular .NET classes as components. You can download Autofac from here.

Our example application is a console program that checks a list of employees and notifies which of them are experts (work experience more than 10 years).