Posted by: Zeeshan Amjad | September 9, 2011

WPF threading with Lambda expression


We saw two examples of threading here and here. But in both cases we are creating delegate to perform the threading. For small tasks it looks like an overwork, when we can do the same thing easily with the help of lambda expression. We can even convert the complete threading methods into lambda expression easily. Here is our lambda expression to create another thread using BeginInvoke method of Dispatcher class.

Code Snippet
Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    (Action)(() =>
    {
        int number;
        int total = 0;

        if (Int32.TryParse(txtNo.Text, out number))
        {
            for (int i = 2; i < number; i++)
            {
                if (IsPrime(i))
                    total++;
            }
        }

        tbResult.Text = total.ToString();
    })
    );

 

Here we do’t use binding or any other WPF specific thing for simplicity and focus only on threading this time. Also note that we have to typecast the lambda expression to Action type, otherwise compile don’t know how to convert this lambda expression to System.Delegate. Because this lambda expression is not taking any parameter therefore we have to put empty parenthesis i.e. ().

In this simple program we asked user to input any number and then calculate the total number of primes up to that number using another thread. In mathematics this is known as Pi function.

Here is complete XAML code of our program.

Code Snippet
<Window x:Class="WpfThreadPrime.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="Threading Prime" Height="200" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center">
            Enter number
        </TextBlock>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="5" Name="txtNo"/>
        <TextBlock Grid.Column="0" Grid.Row="1" Margin="5"
                   VerticalAlignment="Center">
            Total number of Primes
        </TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="1" Margin="5" Name="tbResult"
                   VerticalAlignment="Center"/>
        <Button Grid.Column="0" Grid.Row="2" Name="btnCalculate"
                Width="75" Height="35" Click="btnCalculate_Click">
            Calculate
        </Button>
        <Button Grid.Column="1" Grid.Row="2" Name="btnExit"
                Width="75" Height="35" Click="btnExit_Click">
            Exit
        </Button>
    </Grid>
</Window>

 

And here is complete C# code of the program.

Code Snippet
using System;
using System.Windows;
using System.Windows.Threading;

namespace WpfThreadPrime
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                (Action)(() =>
                {
                    int number;
                    int total = 0;

                    if (Int32.TryParse(txtNo.Text, out number))
                    {
                        for (int i = 2; i < number; i++)
                        {
                            if (IsPrime(i))
                                total++;
                        }
                    }

                    tbResult.Text = total.ToString();
                })
                );
        }

        private bool IsPrime(int number)
        {
            for (int i = 2; i < number; i++)
            {
                if (number % i == 0)
                    return false;
            }

            return true;
        }
    }
}

 

Here is the output of the program if we input 1,000,000 in the textbox and press the calculate button. Of course it takes some times depends on the computer configuration and how many process are running at that time.

ThreadingLambdaOutput

Advertisements

Responses

  1. […] We already saw one example of using Lambda expression in WPF threading here. But there is one major problem in that program. If we enter a very large number, say 10 million, […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: