My Advices for Parallel and Async programming.

The biggest reason I’m writing this post, is when I started to write async and await pattern,there were few questions about this pattern, and this post going to explore them.

What is the difference between Parallel and Async?

To answer this question, we need to ask the following Question:

Is it CPU bound or I/O bound work?

CPU-bound work means: we want to iterate over big in memory collection of objects, by using the TPL like PLINQ, Parallel.For, Parallel.Foreach, or we want to execute very complex calculation process.

When we use the Task Parallel Library the compiler feel out how many threads needed to make the best progress to our job.

Good to know that use of TPL not always run in parallel, and increase throughput on a machine that’s under load.

For example:

If we have list of person object and we want to sort the list as parallel, use the following code:

var orderedPersons = Persons.AsParallel().OrderBy(x => x.Age);

I/O bound work means: we write code that’s bound by the time of network or I/O requests, and then we need to use Asynchronous code.

By using the async and await pattern the compiler generates the appropriate code, to do the asynchronous job behind the scene.

Async Behind the Scene:

In the .NET 4.5, when any method marked with the async and await, the compiler implement the method into two code blocks:

Stub method – contains the initial set up information for the asynchronous method, and starts the state machine generated by the c# compiler.

State machine – maintains the state of the asynchronous method, where it start and where he need to be after the asynchronous process finish.

For example:

If we have a WPF application that responds to button click event, and the click event needs to download data from the server asynchronously:

async void Button_Click(object sender, RoutedEventArgs e){

await LoadDataAsync();

}

async Task LoadDataAsync(){

await DownloadAsync();

}

When the compiler encounter’s the await keyword he return the work flow back to the caller, so if the await call come from the UI thread, that means the program stay responsive to the UI interaction. When the answer comes from the network, then the Task marked as completed and the compiler jump to the point he awaited.

Async void is a fire and forget mechanism:

  1. When we write Async void method, the method return void to the caller so the caller is unable to know when the async void work has finished.
  2. Exceptions and Async void methods, when exception thrown from async void method, the caller is unable to catch the exception, and it throws strait to the UI thread or the main thread, and that’s can crash the entire application.

Cancelling Async Operation:

If we want to implement cancellable async operation, we can use the overload Task method that accepts a System.Threading.CancellationToken.

CancellationTokenSource cts = new CancellationTokenSource();

private Task<IEnumerable<Person>> LoadDataAsync()

{

Task<IEnumerable<Person>> res = new Task<IEnumerable<Person>>(obj =>

{

return GetData();

}, cts);

res.Start();

return res;

}

If the token has cancellation requested and the asynchronous operation is able to respect that request, the returned task will end in the TaskStatus.Canceled state; there will be no available Result and no Exception.

Summary:

Then if we decide to parallelize our code, we need to keep in mind the following details:

  • Async pattern is useful for IO and network bound work.
  • TPL pattern is usefule for data bound work.
  • Async void is fire and forget mechanism.
  • Async doesn’t solve everything.
  • TPL not always runs in parallel.

Want to learn more?

http://blogs.msdn.com/b/lucian/archive/2013/06/28/talk-the-complete-async-three-talks-from-teched-europe-2013.aspx

Advertisements
Posted in .NET 4.5, C# 5 | Leave a comment

Little Difference between c#4 and c#5 compiler

What is the difference between outside declared variable and inside declared variable?

Case1:

Outside:

var i_ = default(int);

foreach (var i in new[] { 0, 1, 2, 3, 4, 5 })

{

i_ = i;

Console.WriteLine(i_);

}

Inside:

foreach (var i in new[]{0,1,2,3,4,5})

{

var i_= i;

Console.WriteLine(i_);

}

In this example the difference is only how the compiler allocate the variables, if the variable declared outside the loop the compiler need to allocate the i_ variable only once, and if  i_ declared inside the loop then for each iteration the compiler need to allocate new variable. But the expected output in this case is same: 0 1 2 3 4 5.

Case2:

Outside:

var fis = new List<Action>();

var i_ = default(int);

foreach (var i in new[]{0,1,2,3,4,5})

{

i_ = i;

fis.Add(() => Console.WriteLine(i_));

}

foreach (var fi in fis)

{

fi();

}

Inside:

var fis = new List<Action>();

foreach (var i in new[] { 0, 1, 2, 3, 4, 5 })

{

var i_ = i;

fis.Add(() => Console.WriteLine(i_));

}

foreach (var fi in fis)

{

fi();

}

In case 2 we capture the loop variable i in closure and copy it into  the i_ variable.

then call the Console.Writeline function. In other words we deferred the print of i variable.

In this case the Outside scenario prints 5 5 5 5 5, and Inside scenario prints the expected result 0,1,2,3,4,5.

But if we don’t care about outside or inside declarations and we write the function as:

var fis = new List<Action>();

foreach (var i in new[] { 0, 1, 2, 3, 4, 5 })

{

fis.Add(() => Console.WriteLine(i));

}

foreach (var fi in fis)

{

fi();

}

In C# 4 the result is like outside declared variable: 5,5,5,5,5.

And in C#5 the result is like inside declared variable : 0,1,2,3,4,5.

Iterate over For loop:

Outside:

var fis = new List<Action>();

//declaring the variable outside the loop

var i_ = new int();

for (i_ = 0; i_ < 5; i_++)

{

fis.Add(() => { Console.WriteLine(i_); });

}

foreach (var fi in fis) fi();

Inside:

var fis = new List<Action>();

for (int i = 0; i < 5; i++)

{

fis.Add(() => { Console.WriteLine(i); });

}

foreach (var fi in fis) fi();

If we iterate over the For loop, the compiler behavior is unchanged.  And the result of For loop examples above is the same : 5,5,5,5,5.

 

So if we want to get the expected result we need to capture the variable inside the loop.

var fis = new List<Action>();

for (int i = 0; i < 5; i++)

{

int i_ = i;

fis.Add(() => { Console.WriteLine(i_); });

}

foreach (var fi in fis) fi();

In this case the result will be 0,1,2,3,4.

Posted in C# 5 | Leave a comment

WPF and DataAnotations

A few weeks ago I took MVC 3 course at E4D with Eyal Vardi.

www.slideshare.net/EyalV/aspnet-mvc-30-validation

One of the subjects we learned is how to validate Object or property-using validation attributes.

First thing I thought about is why WPF does not support Data Annotations validation?

Validation and WPF:

  1.    The Classic way:

Throw an error exception from the property set method.

For example:

    private string _albumName;
    public string AlbumName
	{
		get {
            return _albumName;
        }
		set
        {

            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("Album name must be specified");
            }
            else
            {
                _albumName = value;
                OnPropertyChanged("AlbumName");
            }
        }
	}

This validation logic is not the best practice to validate property because we don’t want to throw exception each time the user entered not valid input.

2.     Validation Rules:

Validation Rules is the WPF data binding built in validation mechanism. By this mechanism, we need to create distinct class like value converter that implement the validation logic and throw exception for invalid data.

For example:

public class AlbumValidationRule : ValidationRule

{

public override validationResult Validate(object value, CultureInfo cultureInfo)

{

                 if(string.IsNullOrEmpty(value))
{

                 throw new ValidationResult(false,“Album name must be specified”);
}

}

}

this mechanism gives us more flexibility and code reuse but it’s very complicated to implement and this mechanism does not support the MVVM pattern because we put logic into the UI.

3.     IDataErrorInfo:

This interface exists since .NET Framework version 1 released. The interface exposes two properties Error and Item the item.

Error property present the validation error message, Item property Invoke each time the binding engine triggered the validation engine.

Validation by DataAnotations and IDataErrorInfo:

By validation attributes, we can minimize the validation code, we can reuse the validation logic and we keep the validation process simple.

This pattern hide all the validation rules and give us very clean business view models,  each property get set of validation attributes defining the validation rules.

To support this pattern I need to add reference to (System.ComponentModel.DataAnnotations namespace) and use the Validator class to verify whether a property is valid.

Let’s look at the Base View Model.

My base view model implements the IdataErrorInfo to support data binding validation:

Base View Model:

public class ViewModelBase:INotifyPropertyChanged, IDataErrorInfo {
   public ViewModelBase()
        {
            ErrorMessage = string.Empty;

        }
        #region Properties

        public string ErrorMessage { get; set; }

        #endregion

}
public string Error
{
      get { return ErrorMessage; }
}

public string this[string columnName]
{
     get { return ErrorMessage; }
}

The SetPropertyValue method invokes each time new data comes to the setter method of the property,

The method sets the property value and check the validation rule to the property.

protected void SetPropertyValue(String propertyName, ref T current    alue, T newValue)
{
   if (currentValue == null)
   {
      if (newValue == null)
                    return;
   }
   else if (newValue != null && currentValue.Equals(newValue))
   {
        return;
   }
       currentValue = newValue;
       ValidateProperty(propertyName, newValue);
       OnPropertyChanged(propertyName);
   }

}

The code bellow responsible for the validation of the given property, the ValidateProperty method gets the property name and his value, by using the TryValidatePropert method of the Validator class we can validate the property.

 protected void ValidateProperty(string propertyName, object value)
 {

    var vrs = new List();
    ErrorMessage =  string.Empty;

      if (!Validator.TryValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName }, vrs))
    {
                IsValid = false;
                foreach (var item in vrs)
                {
                  ErrorMessage =  string.Join(Environment.NewLine, vrs.Select(x => x.ErrorMessage));
                }
            }
            else
            {
                IsValid = true;
            }

        }

View Model:

Album view model inherits from BaseViewModel.

Above each property, we put a set of validation attributes and by SetPropertyValue method we set the property value

public class AlbumViewModel : ViewModelBase
{
    private int _length;

    [Required(ErrorMessage = "Length must be specified")]
    [Range(0, 200)]
    public int Length
    {
       get
       {
         return _length;
       }
       set
       {
         this.SetPropertyValue("Length", ref _length, value);
       }
    }
}

View:

 <TextBox Text="{Binding Path=Length, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
                        ValidatesOnDataErrors=True,
                        ValidatesOnExceptions=True,
                        NotifyOnValidationError=True}"
           Validation.ErrorTemplate="{StaticResource validationTemplate}"         
           Grid.Column="2"
           Grid.Row="3"/>

To indicate the user when his input is invalid we need to set NotifyValidationError to true, this property activate the validation engine of the data binding, we set also the ValidatesOnDataErrors and ValidatesOnExceptions to support all validation implementation ways.

As you can see, using Data Anotations validation gives us elegant and clean way to support validation rules on property. With this pattern we can create custom attributes to support more complex validation rules, and if we want we can use our attributes collection in any other project.

Available validation frameworks:
1.     Validation Toolkit : http://validationtoolkit.codeplex.com/ 
Validation Toolkit for WPF & Silverlight displays automatically validation errors coming from both Data Annotations on the View Model and Asynchronous calls to Web Services. The View Model is wrapped into an object that supplies all needed interface implementations.

2.     WPF Application Framework: http://waf.codeplex.com/
The WPF Application Framework (WAF) is a lightweight Framework that helps you to create well structured WPF Applications. It supports you in applying a Layered Architecture and the Model-View-ViewModel (aka MVVM, M-V-VM, PresentationModel) pattern.

3.     Microsoft Enterprise Library :  http://entlib.codeplex.com/
This framework including the Validation Application Block uses the same general approach—validating an object against a set of
rules defined using attributes (data annotations) or an external XML file.
Posted in .NET, WPF | Leave a comment

Event Aggregator VS Dependency Injection

For many Weeks, I have herd peoples saying they use Event Aggregator in prism as main publish/subscribe event mechanism.

When I started using this technology, I asked myself why?

Is Dependency Injection not good enough?

After a little research, I concluded that Dependency Injection could do the same job with less chance of bugs.

For Example, if we have Master Details Application with two modules: Tree Module and Details Module.

Event Aggregation Pattern in Master Details Application

If the Details Module want to know if selected item changed, Details module need to register to particular event but he don’t know if the publisher exists.

On the other hand, the publisher can send event but he do not know if this event have subscribers.

The Publisher:

Private void OnSelectedItemChanged(object selectedObject){

EventAggregator.GetEvent<SelectedItemChangedEvent>().publish(selectedObject);

}

The Subscriber

Private void SubscribeToEvent(){

EventAggregator.GetEvent<SelectedItemChangedEvent().Subscribe(OnSelectionChange);

}

Private void OnSelectionChanged(object eventArgs)

{

//Do something

}

In our loosely coupled spaghetti code the publisher, don’t know if anyone listening and reacting to the fired event.

It make sense that if the publisher fire event he should know if this event have subscribers and here the benefit of “Dependency Injection” it keeps the loosely couple pattern but Verifies react when firing event.

Communication with Dependency Injection

public interface ISelectionObserver
    {
        ViewModelBase SelectedViewModel { get; set; }

        event EventHandler SelectedChanged;
    }

Here the TreeViewModel implement the ISelectionObserver interface that define all the public functions require to send SelectedChanged event

public class TreeViewModel : ViewModelBase, ISelectionObserver

public class TreeViewModel : ViewModelBase, ISelectionObserver
{
 public event EventHandler SelectedChanged;
        private void OnSelectedItemChanged()
        {
            if (SelectedChanged != null)
            {
                SelectedChanged(this, EventArgs.Empty);
            }
        }

}

DetailsViewModel do not know who is Implementing ISelectionObserver and he don’t care about it.

 public class DetailsViewModel : ViewModelBase
    {
        #region fields
        ISelectionObserver _selectionObserver;
        #endregion
        public DetailsViewModel(ISelectionObserver selectedobserver)
        {
            _selectionObserver = selectedobserver;
            _selectionObserver.SelectedChanged += (sender, e) =>
            {
                this.SelectedChanged();
            };
        }

        void SelectedChanged()
        {
            this.Data = _selectionObserver.SelectedViewModel;
        }

}

BootsTrapper is responsible to inject the ISelectionObserver implementation component to DetailsViewModel.

Benefits of using Dependency Injection

  • Keeps loosely coupled pattern.
  • More testability.
  • The implementation is simple, and enable code reuse.
  • Reduces Dependence of technology (Prism).

Conclusion

 

Conceptually, in real world if something happens then the response should come, as well as in our programming world.

For example, if fire broke out then the publisher must to know that someone listen to the event, what EventAggregator does not provide

In addition, Dependency Injection does.

So if we look from responsibility side,

Dependency Injection gives us better way to communicate between loosely coupled components.

Posted in WPF | Leave a comment

Reactive Extensions

My First experience with Reactive Extensions and .NET 4.5.

What are reactive extensions?

Reactive extension come to collect the commonality between things, if we look at collections, all .NET collections are implement IEnumerable interface, and this collections are pull-based collections, so if we iterate over the collection we need to pull each element we want by GetEnumerator().

However, Reactive Extensions come to replace pull-based collections into push-based collections.

Why?

Because we want to support Async programming model. When the client send request to the server,  the server will push the result (event) to the client when the data ready.

Enumerables  – a pull based world

interface IEnumerable<out T>

{

IEnumerator<T> GetEnumerator();

}

Basically if we look at IEnumerable, this interface is very synchronous interface because the client need to pool the data, and if the data not ready yet,  and we do it on the UI thread then the UI will get stuck.

Observable  – a push based world

    interface IObservable<out T>
    {
        IDisposable Subscribe(IObserver<T> observer);
    }
public interface IObserver<in T>
{
      void OnCompleted();
      void OnError(Exception error);
      void OnNext(T value);
}

In push-based world, we have the Observer that react to events that coming from the
Observable. For example if we subscribe to MSDN magazine rss we post a mail address to react when new magazine come out. So the mail address is the “Call back” and the producer have the ability to “Send event” when new Magazine is out – so the idea is that the data pushed into the Observer.

Therefore, my first application with RX,  is a simple observable and observer:

class Program
{
static void Main(string[] args)
{
//Sender and a reciever of Data
var subject = new Subject<int>();
subject.OnNext(42);
//First subscriber to the observable
var d1 = subject.Subscribe(x => Console.WriteLine(“1>” + x));

subject.OnNext(43);

//Second subscriber
var d2 = subject.Subscribe(x => Console.WriteLine(“2>” + x));

subject.OnNext(44);

d1.Dispose();

subject.OnNext(45);
Console.ReadLine();

}
}

And the result is:

1>43

1>44

2>44

2>45

Conclusion:

With Reactive extension the client can subscribe to events streams coming from the server and in the meantime, the client can do anything else till event coming and the call back method will react to the event from the Observer.

Posted in .NET 4.5 | Leave a comment

WPF VIRTUALIZATION

What is Virtualization:

Virtualization is a key component of Dynamic IT.

Virtualization helps isolate various computing resources.

With virtualization, computing components are essentially turned into-on-demand services.

If you trying to display more than 10,000 without Virtualized panel you run the risk of getting performance, responsiveness, and stability issues of your WPF Application.

In WPF Items controls such ListBox and TreeView use VirtualizedStackPanel as their default panel, to improve performance.

For example if we want to display 10,000 items on a ListBox box without VirtualizedStackPanel,

It will take for core i5 processor 9.068 seconds to load (first time loading) the application.

 <ListBox
            Grid.Row="3"
            ItemsSource="{Binding Path=Appointments}"
            ItemTemplate="{StaticResource ResourceKey=ListBoxAppointmentTemplate}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel 
                        Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

On  the other hand if we load 10,000 items on a ListBox that support virtualization its take only 226 milliseconds to load the application.

<ListBox
            Grid.Row="3"
            ItemsSource="{Binding Path=Appointments}"
            ItemTemplate="{StaticResource ResourceKey=ListBoxAppointmentTemplate}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel 
                        Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

Next post will cover how to implement custom virtualized panel.

Posted in WPF | Leave a comment