Monday, June 10, 2013

WPF Threading and Dispatcher

1. Thread and Thread Pool
2. way to create Thread.
3. WPF and CheckAccess
4. Begin Invoke and Invoke
5.Notifier
6. Invoke Required
7.IDispatcher

Working With The WPF Dispatcher


Proper use of threads can greatly increase the responsiveness of your WPF applications. Unfortunately, you can't update any UI controls from a thread that doesn't own the control. In .NET 2.0, you used Control.Invoke(). Now, we've got something similar but more powerful - the Dispatcher. This tutorial will explain what the Dispatcher is and how to use it.
First of all, you need to know where the Dispatcher lives. Every Visual (Button, Textbox, Combobox, etc.) inherits fromDispacterObject. This object is what allows you to get a hold of the UI thread's Dispatcher.
The Dispatcher is why you can't directly update controls from outside threads. Anytime you update a Visual, the work is sent through the Dispatcher to the UI thread. The control itself can only be touched by it's owning thread. If you try to do anything with a control from another thread, you'll get a runtime exception. Here's an example that demonstrates this:
public partial class Window1 : Window
{
  public Window1()
  {
    InitializeComponent();

    CheckBox myCheckBox = new CheckBox();
    myCheckBox.Content = "A Checkbox";

    System.Threading.Thread thread = new System.Threading.Thread(
      new System.Threading.ThreadStart(
        delegate()
        {
          myCheckBox.IsChecked = true;
        }
    ));

    thread.Start();
  }
}
This code creates a Checkbox, then creates a thread which tries to change the checked state. This will fail because the Checkbox was created on a different thread than the one trying to modify it. If you run this code, you'll end up with this exception:
The calling thread cannot access this object because a different thread owns it.
So the question is, how do you update the Checkbox from this thread? Fortunately, the Dispatcher gives us the ability to Invoke onto its thread. Invoking probably looks really familiar if you've programmed in .NET 2.0. We actually have an in-depth tutorial on invoking that you might want to read. Below is code using the Dispatcher that will run and update the Checkbox without throwing an exception.
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        myCheckBox.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));
      }
  ));

  thread.Start();
}
Now we've introduced the Dispatcher object. The call to Invoke needs to take a few pieces of information. First is the priority you'd like your work executed with. Next is the delegate that contains the work you actually want to do. If your delegate takes parameters, the Invoke call will also accept an Object or Object[] to pass into the delegate function. It will also accept a timespan that limits the amount of time the Invoke call will wait to execute your code.
The call to Invoke will block until your function has been executed. Depending on the priority you've set, this might take a while. The Dispatcher also has the ability to invoke code asynchronously usingBeginInvoke. Let's look at the same example using BeginInvoke.
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        System.Windows.Threading.DispatcherOperation
          dispatcherOp = myCheckBox.Dispatcher.BeginInvoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));

        dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
      }
  ));

  thread.Start();
}

void dispatcherOp_Completed(object sender, EventArgs e)
{
  Console.WriteLine("The checkbox has finished being updated!");
}
BeginInvoke takes many of the same arguments as Invoke, but now returns a DispatcherOperationthat lets you keep track of the progress of your function. In this case, I simply hooked the Completed event that notifies me when the work has been completed. The DispatcherOperation object also lets you control the Dispatcher by changing its priority or aborting it all together.
As I mentioned above, we can limit the amount of time an Invoke is allowed to take my passing the Invoke call a TimeSpan structure. Here's an example that will wait 1 second for the queued function to complete:
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        myCheckBox.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.SystemIdle,
          TimeSpan.FromSeconds(1),
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));
      }
  ));

  thread.Start();
}
Unfortunately, there's no way to determine if the invoke finished or timed out from the outside. You can always put code inside the invoked function to determine if it executed.
All right, so we've got our dispatchers working and code is being executed where it's supposed to be. Invokes, however, are kind of an expensive process. What happens when your controls are being updated from both external threads and the main UI thread. How do you know if you're supposed to use Invoke? The Dispatcher object provides a function that tells you whether or not you have to use Invoke. In WinForms you call InvokeRequired on the actual control. In WPF, you call CheckAccess() on the Dispatcher object. CheckAccess() returns a boolean indicating whether or not you can modify the control without Invoking.
if (!myCheckBox.Dispatcher.CheckAccess())
{
  myCheckBox.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.Normal,
    new Action(
      delegate()
      {
        myCheckBox.IsChecked = true;
      }
  ));
}
else
{
  myCheckBox.IsChecked = true;
}
So now, before I invoke, I check to see if I even need to. If I do, I invoke the function, if I don't, I simply update the control directly.
As you can see, the Dispatcher provides a great deal of flexibility over the WinForms Invoke. There's a lot about WPF's dispatching model that we didn't touch in this tutorial. TheSystem.Windows.Threading namespace contains a lot more useful objects that extends the power of the dispatcher even further.


Saturday, June 8, 2013

WPF Interview Question and Answer part I



What is WPF?

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

What is the need of layout panels in WPF?

Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

What are the different types of layout panels in WPF?

There are mainly 5 types of layout panels in WPF. These are: 

Grid Panel
Stack Panel
Dock Panel
Wrap Panel
Canvas Panel

What is XAML

XAML (pronounced as Zammel) is a declarative XML-based language by which you can 
define object and properties in XML. XAML document is loaded by a XAML parser. 
XAML parser instantiates objects and set there properties. XAML describes objects, 
properties and there relation in between them. Using XAML you can create any kind of 
objects that means graphical or non-graphical. WPF parses the XAML document and 
instantiates the objects and creates the relation as defined by XAML.

What is Attached Properties
These are dependency properties that belong to one class but can be used in another. 
Consider the below code snippet:- 
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> 
4 7 9 
Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas. 
Left is dependency property as it belongs the canvas class. It’s used by the Rectangle to 
specify its position within Canvas.

What is Routed Event
In a typical WPF application, it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

What are core adssembly of WPF
WindowsBase.dll:- It defines the core types constituting the infrastructure of WPF API. 

PresentationCore.dll:- Defines numerous types constituting foundation of WPF GUI layer. 

PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services. 

Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer.

What is the use of System.Windows.Media namespace?
It is the root namespace to several other media related namespaces. It provides different types to work with animations, 3D rendering, text rendering and other multimedia services.