Infragistics ASP.NET controls

Dependency Injection and Inversion of Control Ioc With the Microsoft Unity Container

Design for Reusability A well designed application should promote code reuse whenever possible.  Code reuse can save you time and money by allowing you to use components from previous applications to solve common problems in new projects.  The task of managing dependencies is one of the many concerns a developer faces when designing for reusability.  Dependencies are any classes that a particular class must directly instantiate and use in order to accomplish a task.  As a rule of thumb, it's good object oriented programming practice to code to an interface rather than a concrete implementation.  This will make your code flexible and built for change.   An example of a dependency You've been tasked to write a console application.  The application requires that the user authenticates before using any of the features and there is a requirement that all successfully log-ins are logged to a text file.  Here is the code for the example. TextLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class TextLogger { public void LogMessage(string message) { //Code to write the message to a text file.... Console.WriteLine(string.Format("Logging the message to a text file: {0} ", message)); } } }   AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { public AuthenticationService() { } internal void Authenticate(string userName, string password) { //Authentication logic goes here TextLogger logger = new TextLogger(); logger.LogMessage("Login was successful"); } } }   Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { class Program { static void Main(string[] args) { AuthenticationService authenticationService = new AuthenticationService(); authenticationService.Authenticate(); } } } This is a basic example for demonstration purposes only.  Now, as you can see in the AuthenticationService Authenticate method we are instantiating an instance of the TextLogger class.  So now a few weeks pass by and the customer wants you to log to a database instead of a text file.  So you create  a new class. DBLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The AuthenticationService was dependent on the TextLogger and is now dependent on the DBLogger class.  The current design requires us to change the AuthenticationService any time the customer requests a new type of logger.  The same holds true for any unit tests that we write that uses a Logger class.  As you can see the design promotes tight coupling because we are coding to a concrete implementation which is not very flexible. Introducing an interface As we can see, both logger classes have one method called LogMessage.  They share the same interface.  This is a perfect example of an instance in which we should code to an interface.  So we start by creating an interface that matches the two logging classes. ILogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public interface ILogger { void LogMessage(string message); } } Now we could simply change the logger declaration in the AuthenticationService and be done with it, however, there are still some optimizations that can be achieved.  For instance, currently the Logger declaration is a local variable inside of the Authenticate method.  Imagine were to inject the ILogger as a parameter of the AuthenticationService constructor.  This is a much more flexible design because the AuthenticationService only has knowledge of an ILogger.  Since the implementation is injected via the constructor, the class is no longer tied to any one specific implementation. Here is the updated AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { //the logger is now a class field private ILogger logger; public AuthenticationService(ILogger implementation) { //The implementation is injected via the constructor logger = implementation; } internal void Authenticate(string userName, string password) { //Authentication logic goes here logger.LogMessage("Login was successful"); } } } DBLogger.cs updated using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger : ILogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The Unity Container The Unity container allows us to use code (or a configuration file) to associate an interface with a class.  This is typically done during your application start up or the set up of your unit tests.  You register your interface and class mappings.  Then later when it's time to instantiate an instance of your objects, you ask the container to resolve an instance of the object that you need.  The Unity container will perform an internal look up and it will resolve any dependencies that your object's constructor depends on.   I prefer to register my interface/class mappings in a class that I call a module.  When my application starts I load all modules to prepare the container to resolve all of the objects that I will need.  This abstraction allows you to easily switch an interfaces implementation at run time providing a high level of flexibility to your code.  Here is a brief example of how to use the Unity container.  You will need to download the Unity assemblies from nuget or from the Microsoft patterns and practices Unity Application block site.http://unity.codeplex.com/ LoggingModule.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { public class LoggingModule { IUnityContainer _iocContainer; public LoggingModule(IUnityContainer container) { _iocContainer = container; } public void Init() { //Add any logic here to look in a config file, check a property //or any other condition to decide which implementation is registered. //register the database logger to the ILogger interface _iocContainer.RegisterType(typeof(ILogger), typeof(DBLogger)); } } } Updated Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { class Program { private static IUnityContainer _iocContainer; static void Main(string[] args) { //create our container _iocContainer = new UnityContainer(); InitializeModules(); //the container knows how to create an AuthenticationService object //as well as what type of ILogger it takes because we registered //the required class in the loggerModule. var authenticationService = _iocContainer.Resolve<AuthenticationService>(); authenticationService.Authenticate("username", "password"); Console.WriteLine("press any key"); Console.ReadKey(); } private static void InitializeModules() { //pass the container to the module //so when we register the types we can resolve them var loggingModule = new LoggingModule(_iocContainer); loggingModule.Init(); } } }   This is a very basic introduction to Unity but you I hope that you can see the possibilities when you program to interfaces and let the container take control of object creation.  You could extend this example to create a ModuleInitializer class that takes the modules that need to be initialized.   The bottom line is Program to interfaces Inject dependencies via the constructor Register your dependency interfaces to the desired class in the unity container.  You can use a module approach if you so choose. As long as your interfaces are mapped to classes in your container, the container can resolve any dependencies that your object requires when instantiated. Download the source  UnityExample.zip (723.64 kb) Happy coding! kick it on DotNetKicks.com


Implementing a re-sizable composite view user interface using the MVVM pattern, the GridSplitter, and WPF UserControls.

  A composite view user interface In the world of WPF, the Model-View-ViewModel pattern is a great way to separate your UI from your business logic.  This decoupling allows you to easily unit test your code.  When implemented correctly, the MVVM pattern promotes a view agnostic structure which makes switching between different views extremely easy.  A composite view UI is basically a user interface that is made up of multiple independent views.  By independent, I mean that the views should be decoupled and unaware of each other.  In this tutorial, I will show you how to create the following UI.     Existing frameworks There are several existing frameworks that facilitate the implementation of the MVVM pattern and composite view applications.  MVVM Toolkit, MvvMLight, SoPrism, and Prism are a few examples of some of the existing libraries out there.  Prism is probably the most complete and extensive but it also has a large learning curve.  I decided that before I dive into learning the details of Prism, I would benefit by trying to code a composite application by hand.  The User Interface design The previous screen shot shows an application made up of a Window that contains a grid, a listview, and a ContentControl.  The ContentControl and ListView are separated by a GridSplitter control.  This allows the two views to be re-sized.  The ContentControl will have a UserControl injected into the content property as the ListView's selected item is changed. Here is the XAML markup <Window x:Class="OutlookLayoutPresenter.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:OutlookLayoutPresenter.Views" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="128*" /> <ColumnDefinition Width="375*" /> </Grid.ColumnDefinitions> <ListView SelectionChanged="lstMenu_SelectionChanged" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MenuDisplayText" x:Name="lstMenu"> </ListView> <ContentControl Grid.Column="1" Content="{Binding Path=Presenter.CurrentView}" x:Name="MainContent"> </ContentControl> <GridSplitter Grid.Column="1" Width="2" HorizontalAlignment="Left" /> </Grid> </Window> As you can see, we have a Grid with two columns.  The column on the left holds a ListView that that is data bound in the code behind.  The ContentControl's content property is also data bound to the Presenter.CurrentView property of our ViewModel.  I chose to implement a presenter object to handle the injection of the UserControl into the ContentControl.  We will start with the codebehind of our view to show how we are setting the DataContext. 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 OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private MainWindowViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainWindowViewModel(); this.DataContext = _viewModel; lstMenu.ItemsSource = _viewModel; } void lstMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { var menuItem = (ViewMenuItems)e.AddedItems[0]; _viewModel.Presenter.DisplayView(menuItem); } } } Note that we have bound our ViewModel to the view's DataContext as well as the ListView's ItemsSource property.  The ViewModel is an ObservableCollection of ViewMenuItem objects.  I created the ViewMenuItem class to contain the region's name and the display text.  The ListView serves as a menu.   Here is the code for the ViewMenuItem class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace OutlookLayoutPresenter { public class ViewMenuItems : INotifyPropertyChanged { private string _regionName; private string _menuDisplayText; public string RegionName { get { return _regionName; } set { if (_regionName == value) return; _regionName = value; OnPropertyChanged("RegionName"); } } public string MenuDisplayText { get { return _menuDisplayText; } set { if (_menuDisplayText == value) return; _menuDisplayText = value; OnPropertyChanged("MenuDisplayText"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } When looking at the ViewModel, please be sure to note the public Presenter property that is used in the data binding of the ContentControl. The ObservableCollection of ViewMenuItem objects builds the ListView menu. Here's the ViewModel's code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; namespace OutlookLayoutPresenter { public class MainWindowViewModel : ObservableCollection<ViewMenuItems> , INotifyPropertyChanged { private IPresenter _presenter; public IPresenter Presenter { get { return _presenter; } set { _presenter = value; OnPropertyChanged("Presenter"); } } public MainWindowViewModel () { this.Add(new ViewMenuItems{RegionName = "RegionOne", MenuDisplayText = "Content One"}); this.Add(new ViewMenuItems{RegionName = "RegionTwo", MenuDisplayText = "Content Two"}); this.Add(new ViewMenuItems{RegionName = "RegionThree", MenuDisplayText = "Content Three"}); this.Presenter = new MainWindowPresenter(); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } All that's left now is the MainWindowPresenter class which will dynamically load one of three user controls based on the ListView's selected item. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Controls; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// This is the presenter class for the main Shell. the purpose of this /// class is to contain all of the UI event handlers for the main shell view. /// </summary> public class MainWindowPresenter : INotifyPropertyChanged, IPresenter { ContentControl _currentView = new ContentControl(); public ContentControl CurrentView { get { return _currentView; } set { _currentView = value; OnPropertyChanged("CurrentView"); } } public void DisplayView(ViewMenuItems item) { switch (item.RegionName.ToUpper()) { case "REGIONONE": this.CurrentView.Content = new ContentOne(); break; case"REGIONTWO": this.CurrentView.Content = new ContentTwo(); break; case "REGIONTHREE": this.CurrentView.Content = new ContentThree(); break; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } There are three user controls that have a different background color and text.  I will show the markup for one of the controls for brevity. <UserControl x:Class="OutlookLayoutPresenter.Views.ContentOne" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Background="Blue"> <Grid> <TextBlock FontWeight="Bold" Foreground="White" Text="Content One" /> </Grid> </UserControl>   As you click on each menu item, the content view will change colors and text.  I've included the source code for your reference. OutlookLayoutPresenterMVVM.zip (93.27 kb)   This concludes the tutorial.  Thanks for reading! Until next time... Buddy James kick it on DotNetKicks.com      


Introducing System.Threading.Tasks namespace. Exploring Action<>, Task<>, and the BusyIndicator.

Introduction The Microsoft .NET framework class library has provided many classes to facilitate complex programming tasks.  Topics like I/O, database management, and sockets were once incredibly tough to implement in languages like C, C++ and VB6.  When .NET was released, it brought with it many classes that abstracted these complex concepts and allowed the developer to concentrate on the business task at hand.  Multithreading is a way of providing asynchronous code execution and is an advanced concept that the framework has greatly simplified.  The System.Threading namespace The System.Threading namespace contains classes to abstract the complexities of multithreaded programming away from the developer.  Multithreading allows you to spawn worker threads to accomplish a unit of code execution.  System.Threading includes classes for synchronizing thread activities as well as accessing shared data .  These classes include; Mutex, Monitor, Interlocked, AutoResetEvent and more.   At the heart of the System.Threading namespace is the System.Threading.Thread class.  This class represents an asynchronous thread of code execution.  The Thread class accepts a delegate to specify a method that returns void and is to be executed independently in regards to the thread that spawned it.  This was one of the first methods of asynchronous programming that was offered to .NET developers. Here's an example using System; using System.Threading; namespace AnsycThread { class Program { delegate void LongRunningComputation(); private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.ReadKey(); } public static void Main(string[] args) { LongRunningComputation codeBlock = LongRunningMethod; Thread spawnedWorker = new Thread(new ThreadStart(codeBlock)); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } This code is not very complicated, especially when compared to the same take written in a language like C or C++.  The System.Threading namespace has been around since the first release of the .NET framework. Enter the System.Threading.Tasks.Task class With .NET 4 came the System.Threading.Tasks namespace.  The idea of a Thread is a low level concept.  To think in terms of processes, threads, and thread management is to think at the level a computers processor.  The Task class was created to abstract these machine level ideas away from the developer so that we could achieve the same solutions that multithreading offers but from the viewpoint of task and workflows instead of threads and processors.  Much like the System.Threading.Thread class, the Task class is simply an asynchronous operation represented by a delegate.  However, there are some key differences.  For instance, there is a generic Taks<T> where T represents the return type of the delegate.  The Task class also handles a lot of the manual aspects of multithreaded programming such as picking a thread from the thread pool, as well as optimization with multicore/multiprocessor systems.  The System.Threading.Tasks namespace event offers functionality to support parallelism, but I'm getting ahead of myself. We are going to examine an example that makes use of the Task class as well as the System.Action class. The System.Action class represents a delegate that takes no arguments and returns void.  There is a generic version of the Action class as well.  It greatly simplifies the syntax of delegates. Consider the following example which is essentially the same as the prior example, except this example uses the Task and Action classes instead of Thread and delegate. namespace AnsycTask { class Program { private static void LongRunningMethod() { //Add a long running computation here for(var loopCounter=0; loopCounter < 100; loopCounter++) { Console.WriteLine(string.Format("The value = {0} ", loopCounter)); } Console.WriteLine("Press a key"); Console.ReadKey(); } public static void Main(string[] args) { Action codeBlock = LongRunningMethod; var spawnedWorker = new Task(codeBlock); spawnedWorker.Start(); Console.WriteLine("The thread has started."); Console.ReadKey(); } } } Accessing the UI from another thread using Dispatcher.BeginInvoke As you can see, multithreaded programming and allow you to complete multiple computing tasks simultaneously.  One of the draw backs of this approach is the fact that you can't directly access controls that were instantiated on the UI thread from your Tasks or Threads.  This is where the System.Windows.Dispatcher class can help.  When you call the BeginInvoke method of the Dispatcher class, it allows you to execute an asynchronous delegate on the same thread that the Dispatcher is associated.  I've included an example that uses the Task, Action, and Dispatcher classes in a WPF application.   This example will execute a Task when the user clicks a button.  The task will open a text file and read the contents of the file.  We use the ContinueWith method of the Task object to specify another Task to run when the first task has completed.  In the ContinueWith Task, we will use the Dispatcher class to set the IsBusy property on a BusyIndicator object.  The BusyIndicator class comes from the WPF Extended toolkit.   Here's the example.. <Window x:Class="FileReadBusyIndicator.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:extToolkit="clr-namespace:Xceed.Wpf.Toolkit;assembly=WPFToolkit.Extended" Title="MainWindow" Height="350" Width="525"> <extToolkit:BusyIndicator x:Name="busyIndicator"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="78*" /> <RowDefinition Height="78*" /> <RowDefinition Height="106*" /> <RowDefinition Height="50*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Content="Load File" Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="118,9,0,0" Name="btnLoadFile" VerticalAlignment="Top" Width="75" Click="btnLoadFile_Click" /> <TextBlock Height="45" HorizontalAlignment="Left" Margin="32,15,0,0" Name="txtDescription" Text="Click the button below to asynchrnously load the contents of the text file specified in the textbox." VerticalAlignment="Top" Grid.ColumnSpan="2" Width="390" /> <TextBlock x:Name="txtContents" Grid.Row="1" ScrollViewer.CanContentScroll="True" Height="183" HorizontalAlignment="Left" Margin="6,0,0,0" Text="rwaraadsadsdsasdafsdfsdafsdaf" VerticalAlignment="Top" Width="491" Grid.ColumnSpan="2" Grid.RowSpan="2"> </TextBlock> </Grid> </extToolkit:BusyIndicator> </Window> And for the codebehind 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.Tasks; using Microsoft.Practices.Unity; using System.IO; using System.ComponentModel; using System.Threading; using System.Windows.Threading; using Xceed.Wpf.Toolkit; namespace FileReadBusyIndicator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private void LongRunningMethod() { //Add a long running computation here for (var loopCounter = 0; loopCounter < 100; loopCounter++) { using (var streamReader = new StreamReader(@"c:\development\openme.txt")) { var contents = streamReader.ReadToEnd(); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.txtContents.SetValue(TextBlock.TextProperty, contents); }, null); } } } public MainWindow() { InitializeComponent(); } private void btnLoadFile_Click(object sender, RoutedEventArgs e) { busyIndicator.IsBusy = true; Action readFile = LongRunningMethod; var spawnedWorker = new Task(readFile); var completedTask = new Action<Task>((t) => { Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { busyIndicator.SetValue(BusyIndicator.IsBusyProperty, false); }, null); }); spawnedWorker.ContinueWith(completedTask); spawnedWorker.Start(); } } } As you can see, the button's click event handler sets the BusyIndicator's IsBusy property to true which will show the ProgressBar.  Next the event handler will create a Task and set it to execute an action that points to a method to read the contents of a file.  The method will use the Dispatcher class to set the TextProperty dependency property of a textbox to the contents of the text file.  When the task completes its execution, it will proceed to execute the task specified in the ContinueWith method which uses the Dispatcher class to set the BusyIndicator's IsBusyProperty dependency property's value to false, causing the ProgressBar to be hidden. You can download the source to the example projects here AsyncTaskExample.zip (352.19 kb). This concludes my introduction to the System.Threading.Tasks namespace. Thanks for reading. ~/Buddy James   kick it on DotNetKicks.com    


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

    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    


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