Infragistics ASP.NET controls

How to keep your WPF UI responsive and report progress during a long running task. C# and asynchronous multithreading.

WPF Succinctly Download

 

 

The problem

Have you ever had to execute a bit of code that took an extremely long time to complete?  If so, I'm sure you've noticed that your user interface becomes unresponsive.  You can't use any controls on the form until the process completes.  This is extremely problematic and makes for a poor user experience.

The cause

This problem is because you have executed a synchronous block of code on the same thread as the user interface.  The user interface will not be able to respond to any user action until the synchronous method has completed.

Let's look at an example that illustrates the execution of a synchronous method executing on the user interface thread.

The example

 

This example is very simple.  It's a WPF application with two buttons.  

One of the buttons will start a long running for loop and the other button opens a MessageBox and

displays a message to let you know that the UI is active.

When you click the button to start the long running process, try to click the other button.  

You will notice that you are unable to click the button to show the message box.

 

Here's the MainWindow.xaml markup

<Window x:Class="SynchronousExecution.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">
    <Grid Width="111" Height="118">
        <Button Content="Start Process" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnStartProcess" VerticalAlignment="Top" Width="89" Click="btnStartProcess_Click" />
        <Button Content="Try to click me" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="btnTryMe" VerticalAlignment="Top" Width="89" Click="btnTryMe_Click" />
    </Grid>
</Window>

 

And here is the code behind MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Threading;

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

        private void btnStartProcess_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Starting the long process.  Try to click the button below.");
            for (var loopCounter = 0; loopCounter < 500; loopCounter++)
            {
                Thread.Sleep(100);
            }
            MessageBox.Show("The process has ended.");
        }

        private void btnTryMe_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("User interface is responding!");
        }
    }
}

Download  SynchronousExecution.zip (52.38 kb)

The solution

The solution to this problem is to spawn a new thread to execute the long running task.  By placing the execution on a seperate thread, this leaves the main UI thread free to interact with the user's input.

Reporting progress 

If you execute a long running task, you usually want to let your users know about the progress of the task.  A control to assist with this is the progressbar control.  

The WPF progress bar control inherits from the RangeBase class.  The control contains the following properties to control how the progress is displayed to the user.

Minimum The minimum value of the Value property.
Maximum The maximum value of the Value property.
SmallChange The value in which the Value property is incremented.
Value The current value position between the Minimum and Maximum property.

Multithreading concerns

Multithreading is a complex topic and is beyond the scope of this article.  However, there are a few concerns that you must be aware of if you plan to access values on the UI thread from the worker thread.

The System.Windows.Threading.Dispatcher object is used to execute code on the UI thread from the executing worker thread.  The Dispatcher object has the BeginInvoke method which will execute an asynchronous delegate on the thread in which the dispatcher object was created.  So by using the dispatcher object from the user interface code you are able to access the user interface controls from your worker thread.

We'll take a look at another example that will bring all of these concepts together to illustrate executing a long running task on a seperate thread with a progress bar that updates the user interface via the Dispatcher object.

The example

The example is a WPF application.  The main window contains the following controls;

lstRandomValues A ListBox control that will hold random values that are generated during the long running process. The pupose of this control is to illustrate the responsiveness of the user interface during the long running process.
prgProgress A ProgressBar control that will illustrate the progress of the long running task. The ProgressBar is hidden by default. It's shown when the long running process begins and is hidden again when the process has ended or is canceled.
txtProgress A TextBox control that displays the long running process percentage of completion.
btnCancel A Button control that will cancel the long running process and in turn hide the progress bar and progress textbox.
btnInteract A Button control that will launch a MessageBox to illustrate the responsiveness of the UI while the long running process is executing.
btnBegin A Button control that will begin the long running process.

And here is the code 

Window1.xaml

<Window x:Class="RandomNameSpace.ViewModels.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="400" Width="400">    
        <!-- Parent Grid -->
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <ListBox Grid.Row="0" Grid.Column="0" Name="lstRandomValues" Grid.ColumnSpan="2" />
        
            <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                
                <Border Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" x:Name="bdrProgress" Visibility="Hidden" Background="Azure" CornerRadius="10" BorderBrush="DarkGray" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center">
                    <StackPanel>
                        <Grid Margin="5">
                            <ProgressBar x:Name="prgProgress" Width="200" Height="20" Minimum="0" Maximum="1" />
                            <TextBlock x:Name="txtProgress" HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Grid>
                        <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right" Margin="3" Click="btnCancel_Click" />
                    </StackPanel>
                </Border>
                
                <Button Grid.Row="1" Grid.Column="1" x:Name="btnInteract" HorizontalAlignment="Center"  Content="Interact with UI" Click="btnInteract_Click" Height="23.96" />
                <Button Grid.Row="1" Grid.Column="0" x:Name="btnBegin" HorizontalAlignment="Left"  Content="Start Long Process" Click="btnBegin_Click"  Height="23.96" Margin="35,33.27,0,33.27" />
            </Grid>
        </Grid>
</Window>

Window1.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Threading;
using System.Windows.Threading;


namespace RandomNameSpace.ViewModels
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : Window 
	{
        private bool IsCanceled = false;

        private RandomViewModel _viewModel;

        public RandomViewModel ViewModel
        {
            get { return _viewModel; }
            set { _viewModel = value; }
        }

		public Window1()
		{
			InitializeComponent();
            PrepareViewModel();
		}

        private void PrepareViewModel()
        {
            ViewModel = new RandomViewModel();

            this.lstRandomValues.DisplayMemberPath = "Value";
            this.lstRandomValues.DataContext = ViewModel;
            this.lstRandomValues.ItemsSource = ViewModel;
        }

		private void btnBegin_Click(object sender, RoutedEventArgs e)
		{
            BeginProcess();
		}

		private void btnInteract_Click(object sender, RoutedEventArgs e)
		{
            MessageBox.Show("Interaction!");
		}

		private void btnCancel_Click(object sender, RoutedEventArgs e)
		{
            CancelProcess();
		}

        public void BeginProcess()
        {
            bdrProgress.Visibility = System.Windows.Visibility.Visible;
            DisableBeginButton();
            Action StartLoop;
            StartLoop = () => DoLongRunningProcess();

            Thread t;

            t = new Thread(StartLoop.Invoke);
            t.Start();
        }

        public void CancelProcess()
        {
            this.IsCanceled = true;
            Thread.Sleep(1500);
            ClearListBox();
            EnableBeginButton();
        }

        private void ClearListBox()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.Clear(); }, null);
        }

        private void DoLongRunningProcess()
        {
            for (var loopCounter = 0.0; loopCounter < 1.0; loopCounter = loopCounter + .1)
            {
                if (!IsCanceled)
                {
                    //add a random number to the viewmodel collection to be bound to the listview
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.ViewModel.AddValue(1564); }, null);

                    UpdateProgressBar(loopCounter);
                    Thread.Sleep(2000);
                }
                else
                {
                    break;
                }
            }

            IsCanceled = false;

            ClearListBox();

            MessageBox.Show("Completed");

            EnableBeginButton();
            HideProgressBar();

        }

        private void EnableBeginButton()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, true); }, null);
        }

        private void DisableBeginButton()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.btnBegin.SetValue(Button.IsEnabledProperty, false); }, null);
        }

        private void UpdateProgressBar(double value)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.prgProgress.SetValue(ProgressBar.ValueProperty, value); }, null);
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtProgress.SetValue(TextBlock.TextProperty, (value * 100).ToString()); }, null);
        }

        private void HideProgressBar()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.bdrProgress.SetValue(Border.VisibilityProperty, Visibility.Collapsed); }, null);
        }
	}
}

 

RandomValue.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace RandomNameSpace.ViewModels
{
    public class RandomValue : INotifyPropertyChanged
    {
        private int _value;

        public int Value
        {
            get
            {
                return _value;
            }
            set
            {
                if (_value != value)
                    _value = value;

                OnPropertyChanged("Value");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

RandomViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace RandomNameSpace.ViewModels
{
    public class RandomViewModel : ObservableCollection<RandomValue>
    {
        public RandomViewModel() : base() {}

        public void AddValue(int value)
        {
            Random rnd = new Random();
            var calculatedValue = (value * rnd.Next(3000));

            this.Add(new RandomValue { Value = (calculatedValue) });
        }
    }
}

Here is the entire solution for download. 

WPFAsyncProgressBarMVVM.zip (77.39 kb)  

This concludes the article.  Thank you for taking the time to read it!

Until next time...

~/Buddy James

kick it on DotNetKicks.com

 

 



Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List

refactorthis.net | WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.
Infragistics WPF controls

WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.

WPF Succinctly Download

 

 

WPF Validation for mere mortals

I've recently jumped on the WPF bandwagon and I've fallen in love with this technology.  XAML is a fascinating animal indeed.  The declarative nature of the language leaves much to be explored.  There are many ways to solve the same problem.  On my quest for knowledge, I've been researching the intrinsic validation functionality of WPF.  Unfortunately, most every example I've ran across on blog posts and codeproject.com have been a bit too complex for my blood.  I find often that you need learn other subjects before you can begin to understand how the validation works.  Don't get me wrong, the examples are really nice.  However, when I'm learning something, I want a straight to the point example of the topic at hand.  It's with this idea in mind that I bring you a simple tutorial on WPF validation.

I will be illustrating this example using the MVVM (Model-View-ViewModel) Pattern.

 

Click here to download the entire source WPFMVVMValidation.zip (74.08 kb)

 Consider the following code 

The view MainWindow.xaml

<Window x:Class="ExceptionValidation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:ExceptionValidation"
        Title="MainWindow" Height="350" Width="525" >
    <Window.Resources>
        <viewModel:MainWindowViewModel x:Key="mainViewModel"/>
    </Window.Resources>
    <StackPanel  DataContext="{Binding Source={StaticResource mainViewModel }}">
        <TextBlock>Enter total amount</TextBlock>
        <TextBox Width="200" Name="txtTotalAmount" >
            <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True">
                <Binding.ValidationRules>
                    <ExceptionValidationRule></ExceptionValidationRule>
                </Binding.ValidationRules>
            </Binding>
        </TextBox>
        <Button Content="Button" Height="28" Name="button1" Width="84" />
    </StackPanel>
</Window>
 

 

The viewmodel MainWindowViewModel.cs

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

namespace ExceptionValidation
{
    class MainWindowViewModel : ObservableCollection<Product>
    {
        public MainWindowViewModel()
        {
            Add(new Product { TotalAmount = 3 });
        }
    }
}
 

The model Product.cs

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

namespace ExceptionValidation
{
    public class Product : INotifyPropertyChanged , IDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private int _totalAmount = 5;

        public int TotalAmount
        {
            get { return _totalAmount; }
            set
            {
                _totalAmount = value;
                OnPropertyChanged("TotalAmount");
            }
        }

        public void OnPropertyChanged(string info)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (PropertyChanged != null)
            {
                handler(this, new PropertyChangedEventArgs(info));
            }
        }


        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get 
            {
                if (columnName == "TotalAmount")
                {
                    bool valid = true;
                    if (_totalAmount > 10)
                    {
                        valid = false;
                    }

                    if (!valid)
                    {
                        return "The total amount cannot exceed 10!";
                    }
                }

                return null;

            }
        }
    }
}

A brief introduction to MVVM 

As you can see, we have a XAML view, a viewmodel class, and a model.  The Model is a representation of an object's data.  In this instance, we are modeling a Product.  The viewmodel is an object that handles the change notification between properties in the model and elements on the view.  XAML properties, events, and bindings have the ability to tunnel (down the tree) as well as bubble (up the tree).  

Binding the ViewModel to the view.

In order to bind the ViewModel to the view, we must make it accessible to the view via XAML.  To accomplish this, we first have to import the namespace in which the viewmodel exists.  Examine the following code.

xmlns:viewModel="clr-namespace:ExceptionValidation"

Here is the equivalent in c#

using ExceptionValidation;

Once we've imported the namespace for use, we then need to define our MainWindowViewModel as a Resource of the current window.

<Window.Resources>
        <viewModel:MainWindowViewModel x:Key="mainViewModel"/>
</Window.Resources>

This allows us to declare an instance of the MainWindowViewModel class by using the associated Key "mainViewModel".

Binding the ViewModel

As stated before the ViewModel acts as a "go between" for the View and the Model.  In order for the view model to communicate with our XAML view, we will bind the ViewModel to the StackPanel's DataContext.

<StackPanel  DataContext="{Binding Source={StaticResource mainViewModel }}">

XAML's ability to tunnel properties down from parent to child will allow each element inside the stack panel to make use of the DataContext binding that we've just setup using the Window resource's key mainViewModel.

ObservableCollection<T>

The viewmodel inherits from ObservableCollection<Product>.  The ObservableCollection<T> generic class represents a collection that can be utilized by WPF databinding.  This is possible because the ObservableCollection<T> class raises an event when items are added and removed from the collection.

INotifyPropertyChanged

The model implements the INotifyPropertyChanged interface.  This interface provides an event in which to fire any time a model property is changed.  This event notifies the bound element in the view that the property has changed.

public event PropertyChangedEventHandler PropertyChanged;

 

public void OnPropertyChanged(string info)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (PropertyChanged != null)
    {
        handler(this, new PropertyChangedEventArgs(info));
    }
}
 

IDataErrorInfo

The magic behind WPF validation comes from the implementation of the IDataErrrorInfo interface.  The interface implements the following members.  The this[columnName] indexer implements the logic of the validation rule.

//Not used by WPF
public string Error
{
    get { throw new NotImplementedException(); }
}

public string this[string columnName]
{
    get 
    {
        if (columnName == "TotalAmount")
        {
            bool valid = true;
            if (_totalAmount > 10)
            {
                valid = false;
            }

            if (!valid)
            {
                return "The total amount cannot exceed 10!";
            }
        }

        return null;

    }
}

The following XAML code binds the TotalAmount property of the first Product in the viewmodel's internal collection to the Text property of the TextBox element.  The ValidatesOnDataErrors attribute tells the textbox binding to raise an event when there is a valadation error.  When the event is raised, the bound element's template is changed to a new visual style that places a Red rectangle around the border of the TextBox.  When the error is corrected, the original template is restored. 

Binding.ValidatesOnDataErrors

<TextBox Width="200" Name="txtTotalAmount" >
    <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True">
    </Binding>
</TextBox>

In the provided example, if you enter a value greater than 10 into the text box and tab out of the textbox, you will see that an error is raised causing the red outline around the textbox.  If you correct the error by replacing the value with a number less than 10, the red outline will disappear.

This concludes my tutorial on WPF validation.  This is the very basic of validation methods.  There are many other advanced tutorials on the subject.  My next tutorial will involve utilizing custom validation attributes from the System.ComponentModel namespace to handle WPF view validation.

Thanks for reading!

~/Buddy James

kick it on DotNetKicks.com  



Comments (2) -

Lasoty
Lasoty
1/29/2013 3:24:11 AM #

HI, thanks for this exaple.
I've one question:
How set disable for IsEnabled button property when textbox has error?

Buddy James
Buddy James
1/29/2013 2:19:49 PM #

Thanks for reading!

You could simply create a property on the Product and or ViewModel and when the validation occurs, if the field is invalid, you can set the appropriate value on the ViewModel.  The ViewModel property should be a Boolean and you can bind it to the IsEnabled property on the Textbox.  So when the field is invalid, you mark a property as false on the ViewModel and the binding will then set the IsEnabled property.  Please let me know if you need a better explanation.  Thanks again for reading!

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List