PIRATED 20130914 1640

PIRATED 20130914 1640

NOTE: This content appears to have been plagiarized. Please leave a comment or email tnwiki at Microsoft (with a link to this article) if we are mistaken. The content was pulled from the following sources:
  • http://blogs.microsoft.co.il/blogs/arik/archive/2010/08/12/wpf-inside-out-dispatcher.aspx
  • http://msdn.microsoft.com/en-us/magazine/cc163328.aspx
The community rules state:
  • "Someone else has relevant content and you want to help them share it with the world. It's a nice thought, but do not copy other people's content to the Wiki, even if the owner said it was OK."



Asynchronous Programming 

Asynchronous programming has both Advantages and Disadvantages. However we can convert disadvantages to advantages if we properly use them, otherwise this can become more cumbersome to program or manage, cause instability in the application, take longer processing time, can consume more bandwidth and make application almost not usable in the production.

The Calculator service demonstrated below represents the scenario:

public void Add()

{

                CalcModel.Add();

}

Public void Sub()

{

CalcModel.Sub();

}

public void Add_Completed(object sender, EventArgs e)

{

//Process Result

}

 Public void Sub_Completed(object sender, EventArgs e)

{

//Process Result

}

The Call Made as below:

CalcViewModel.Add();

CalcViewModel.Sub();

In the above code which returns the result first and which returns result last, the developers will not be able to predict, it will be hard to block the UI thread till all results are returned. Hard to synchronize all items. It will be very difficult to dispose service. The services have the inner Channel which is unmanaged and need to be dispose or else memory consumption will be high. There are many instance we see where Silverlight or WPF application hangs the UI, which makes the application very unfeasible at the production.

The same implementation with Async and Await keywords, available in .NET 4.5, or Async CTP for 2010.

 

public int Task<int> Add(int a, int b)

{

                return CalcModel.Add(a, b);

}

public int Task<int>Sub(int a, int b)

{

return CalcModel.Sub(a, b);

}

 

The Call Made as below:

int res = await CalcViewModel.Add();

int res1 = await CalcViewModel.Sub();

 

This bridges the gap between Asynchronous and synchronous programming and returns the result in efficient fashion, and also addresses all the problems stated above.

 

Dispatcher

 

WPF run on multi-threaded apartment, since there are multi-threads running it’s very easy to get into situation of deadlocks, concurrency management is trivial of WPF applications. Most objects in WPF derive from DispatcherObject. WPF is based on messaging system implemented by the Dispatcher.  This is very similar to Win32 message pumps.

There are two main things with respect to concurrency in WPF.

  • Dispatcher.
  • Thread Affinity.

 

 

The Dispatcher class is used to perform work on his attached thread. It has a queue of work items and it is in charge of executing the work items on the dispatcher thread.

Almost every WPF element has thread affinity. This means that access to such an element should be made only from the thread that created the element. In order to do so, every element that requires thread affinity is derived, eventually, from DispatcherObject class. This class provides a property named Dispatcher that returns the Dispatcher object associated with the WPF element.

If you want to make Async calls you should only make using:

Dispatcher.CurrentDispatcher.BeginInvoke(

....

);

i.e. only through dispatcher otherwise get runtime errors, that thread Id is different from thread which updated it.

Dispatchers object hierarchy:

Disp.gif

 

In the above we can see all objects are derived from dispatcher object and handles concurrency in more effective way.

Using the Dispatcher

The Dispatcher class provides a gateway to the message pump in WPF and provides a mechanism to route work for processing by the UI thread. This is necessary to meet the thread affinity demands, but since the UI thread is blocked for each piece of work routed through the Dispatcher, it is important to keep the work that the Dispatcher does small and quick. It is better to break apart larger pieces of work for the user interface into small discrete blocks for the Dispatcher to execute. Any work that doesn't need to be done on the UI thread should instead be moved off onto other threads for processing in the background.

Typically you will use the Dispatcher class to send worker items to the UI thread for processing. For example, if you want to do some work on a separate thread using the Thread class, you could create a ThreadStart delegate with some work to do on a new thread as shown below.

   Updating UI with Non-UI Thread—The Wrong Way

// The Work to perform on another thread

ThreadStart start = delegate()

{

    // ...

 

    // This will throw an exception

    // (it's on the wrong thread)

    statusText.Text = "From Other Thread";

};

 

// Create the thread and kick it started!

new Thread(start).Start();

 

This code fails because setting the Text property of the statusText control (a TextBlock) is not being called on the UI thread. When the code attempts to set the Text on the TextBlock, the TextBlock class internally calls its VerifyAccess method to ensure that the call is coming from the UI thread. When it determines the call is from a different thread, it throws an exception. So how can you use the Dispatcher to make the call on the UI thread?

The Dispatcher class provides access to invoke code on the UI thread directly. The below shows the use of the Dispatcher's Invoke method to call a method called SetStatus to change the TextBlock's Text property for you.

   Updating the UI

// The Work to perform on another thread

ThreadStart start = delegate()

{

  // ...

 

  // Sets the Text on a TextBlock Control.

  // This will work as its using the dispatcher

  Dispatcher.Invoke(DispatcherPriority.Normal,

                    new Action<string>(SetStatus),

                    "From Other Thread");

};

// Create the thread and kick it started!

new Thread(start).Start();

The Invoke call takes three pieces of information: the priority of the item to be executed, a delegate that describes what work to perform, and any parameters to pass into the delegate described in the second parameter. By calling Invoke, it queues up the delegate to be called on the UI thread. Using the Invoke method ensures that you are going to block until the work is performed on the UI thread.

As an alternative to using the Dispatcher synchronously, you can use the BeginInvoke method of the Dispatcher to asynchronously queue up a work item for the UI thread. Calling the BeginInvoke method returns an instance of the DispatcherOperation class that contains information about the execution of the work item, including the current status of the work item and the result of the execution (once the work item has completed). The use of the BeginInvoke method and the DispatcherOperation class is shown below.

   Updating the UI Asynchronously

// The Work to perform on another thread

ThreadStart start = delegate()

{

    // ...

 

    // This will work as its using the dispatcher

    DispatcherOperation op = Dispatcher.BeginInvoke(

        DispatcherPriority.Normal,

        new Action<string>(SetStatus),

        "From Other Thread (Async)");

   

    DispatcherOperationStatus status = op.Status;

    while (status != DispatcherOperationStatus.Completed)

    {

        status = op.Wait(TimeSpan.FromMilliseconds(1000));

        if (status == DispatcherOperationStatus.Aborted)

        {

            // Alert Someone

        }

    }

};

 

// Create the thread and kick it started!

new Thread(start).Start();

 

 

Background Worker

 

There are many instances, where developer encounters taking long time to update UI, for example moving from login screen to application or clicking on menu opens the particular module or screen. It takes long time if amount of data to be displayed to be huge or have complex graphics to be displayed.

In WPF, it’s very easy to handle these components through Background worker, for better UI responsiveness and fast loading on the screen so that user doesn’t see the delay.

Now that you have a sense of how the Dispatcher works, you might be surprised to know that you will not find use for it in most cases. In Windows Forms 2.0, Microsoft introduced a class for non-UI thread handling to simplify the development model for user interface developers. This class is called the BackgroundWorker. The below shows typical usage of the BackgroundWorker class.

   Using a BackgroundWorker in WPF

BackgroundWorker _backgroundWorker = new BackgroundWorker();

 

...

 

// Set up the Background Worker Events

_backgroundWorker.DoWork += _backgroundWorker_DoWork;

backgroundWorker.RunWorkerCompleted +=

    _backgroundWorker_RunWorkerCompleted;

 

// Run the Background Worker

_backgroundWorker.RunWorkerAsync(5000);

 

...

 

// Worker Method

void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)

{

    // Do something

}

 

// Completed Method

void _backgroundWorker_RunWorkerCompleted(

    object sender,

    RunWorkerCompletedEventArgs e)

{

    if (e.Cancelled)

    {

        statusText.Text = "Cancelled";

    }

    else if (e.Error != null)

    {

        statusText.Text = "Exception Thrown";

    }

    else

    {

        statusText.Text = "Completed";

    }

}

 

The BackgroundWorker component works well with WPF because underneath the covers it uses the AsyncOperationManager class, which in turn uses the SynchronizationContext class to deal with synchronization. In Windows Forms, the AsyncOperationManager hands off a WindowsFormsSynchronizationContext class that derives from the SynchronizationContext class. Likewise, in ASP.NET it works with a different derivation of SynchronizationContext called AspNetSynchronizationContext. These SynchronizationContext-derived classes know how to handle the cross-thread synchronization of method invocation.

In WPF, this model is extended with a DispatcherSynchronizationContext class. By using BackgroundWorker, the Dispatcher is being employed automatically to invoke cross-thread method calls. The good news is that since you are probably already familiar with this common pattern, you can continue using BackgroundWorker in your new WPF projects.

 

Source

This topic was mostly copied from this blog and this MSDN article.
 

Leave a Comment
  • Please add 3 and 2 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Carsten Siemens edited Revision 2. Comment: Pirated Content - see my comment

  • XAML guy edited Revision 1. Comment: added references

  • Fernando Lugão Veltem edited Original. Comment: added toc

Page 1 of 1 (3 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • The images are not displaying can you look into it

  • Fernando Lugão Veltem edited Original. Comment: added toc

  • XAML guy edited Revision 1. Comment: added references

  • Added link to original source, see the images there ;)

  • Carsten Siemens edited Revision 2. Comment: Pirated Content - see my comment

  • NOTE: This article was reported as Pirated/Plagiarized Content (content you didn't write) and will be removed. Please do not steal content from others. If you feel we are mistaken, please leave a comment or email tnwiki at Microsoft with a link to this article and with clear and detailed reasons why you own the content or have explicit permission from the author.

    Content was taken from:

    * blogs.microsoft.co.il/.../wpf-inside-out-dispatcher.aspx

    * msdn.microsoft.com/.../cc163328.aspx

Page 1 of 1 (6 items)