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