A-synchronism in Windows 8 App Development


This will be the last of our series Asynchronous programming.Now since we have a strong background of tasks,this will be very easy to grasp since from C# 5.0,asynchronous has been heavily simplified to represent closely its synchronous counter part.

We have two new keywords called async and await which we will be using.I will be referring to my previous posts .

Our demo app looks like this .The third column having textblocks for comments

image

Scenario 1 : Heavy work without using await .

So lets see the code for the No Await button

   1: start2.Text = System.Environment.TickCount.ToString() ;

   2:            AsyncDownloadFeed();

   3:            stop2.Text = System.Environment.TickCount.ToString();

AsyncDownloadFeed downloads news off the BBC website and also runs a synchronous piece of loop

Lets look at the code behind AsyncDownloadFeed.

   1: public async void AsyncDownloadFeed()

   2:         {

   3:             String url = "http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#";

   4:             HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   5:             Task<WebResponse> response =  WebRequestObject.GetResponseAsync();

   6:             resp = await response;

   7:             comments_Copy.Text = "Loop Starting";

   8:            insaneSynchronousLongLoop();

   9:            comments_Copy.Text = "Loop Finished";

  10:             processNews();

  11:         }

yes I know I have used await here but bear with me.Treat this function as a blackbox.Next is the synchronous loop

   1: private  async void  insaneSynchronousLongLoop()

   2:         {

   3:             // comments.Text = "I am in the loop";

   4:             comments.Text = "I am in the loop";

   5:             int i = 0;

   6:             for (i = 0; i < 1000000000; i++) ;

   7:             comments.Text = "loop finished";

   8:         }

Click on the No await button and we will see, the difference between start time and end time is only 20 miliseconds apart.As expected,the textblocks populates even before the function AsyncDownloadFeed is completed.

image

If we wait a few seconds, we will finally see the result.

image

We already know this phenomenon as its not waiting for the function call to finish.

1.Why does it not wait for the function? It should have been synchronously waiting.?

Answer: Using the “async” keyword isnt the what causing the asynchronous behaviour.The async keyword single handedly cannot be used to transform any synchronous code into non asynchronous one.Async keyword just informs the compiler that there may be code which would need to be run asynchronously. So what is the cause ? Lets examine the AsyncDownloadFeed function by providing two outputs.

   1: public async void AsyncDownloadFeed()

   2:         {

   3:

   4:             String url = "http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#";

   5:             HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   6:             Task<WebResponse> response =  WebRequestObject.GetResponseAsync();

   7:             Debug.WriteLine("Started Awaiting");

   8:             var start = System.Environment.TickCount;

   9:             resp = await response;

  10:             var stop = System.Environment.TickCount;

  11:             Debug.WriteLine("End Await Duration="+(stop-start).ToString());

  12:

  13:             Debug.WriteLine("Loop Starting");

  14:             insaneSynchronousLongLoop();

  15:             Debug.WriteLine("Loop Ending");

  16:             processNews();

  17:         }

Task<WebResponse> response =  WebRequestObject.GetResponseAsync(); is familiar since we already are acquainted with TPL.

resp = await response; is the place where the magic occurs.This tells the compiler that it needs to wait for the response but in such a way,so that it does not block the UI.But this is not similar to “wait” as not only does it not block the UI,the compiler moves on to the next statement .Which means,the insaneSynchronousLongLoop() runs even before the webresponse is returned.Moreover in the insaneSynchronousLongLoop does not block the UI since its running on a different thread.

Another thing is ,we can manipulate the UI within the insaneSynchronousLongLoop () since the compiler takes care of that updating the UI only when the threads return to the main UI.

Advertisements

Introduction to the Windows Phone platform


Shared Windows Core

Windows 8 and Windows Phone 8 Share Many Components At The Operating System Level

Shared Core means

• OS components such as the kernel, networking, graphics support, file system and multimedia are the same on both Windows 8 and Windows Phone 8

• Hardware manufacturers work with the same driver model on both platforms

• Windows Phone gets the support for multi-core and other hardware features that Windows has had for years

• These solid, common foundations makes it easier to extend the Windows Phone platform into the future

It doesn’t mean

• Windows 8 and Windows Phone 8 developers work to exactly the same APIs

• (though you will see more commonality as new features are introduced to both platforms in the future)

Windows Phone 8 supports

• Managed app dev using the WP7.1, WP8.0 .NET and WinPRT APIs

• Native app dev using WinPRT and Win32

• Games dev using the WP7.1 XNA framework

• Games dev using Direct3D or DirectX

clip_image002

Since we are going to look at managed app dev , let me point you to the classes you can use for WP 8 development. There are basically two sets of API s

clip_image004

Now which one should you choose ?

Windows phone .NET API

This has full support windows phone 7.1 classes. So if you code using these supported classes, your app will run on WP 7 two. If you have existing app that runs for WP 7.1,you do not have to re-develop from scratch, you can reuse the existing code base. Contains classes and types from the System and Microsoft.Phone namespaces

• There have been new classes added for Windows Phone 8.0, for example

• Microsoft.Phone.Wallet

• Microsoft.Phone.Tasks.ShareMediaTask

• Microsoft.Phone.Tasks.MapsTask

• Microsoft.Phone.Storage.ExternalStorage

• Microsoft.Phone.Networking.Voip

Windows Phone Runtime API

Windows Phone Runtime is a subset of the full WinRT, plus some phone-specific additions. Windows (Phone) Runtime is implemented in C++ and projected into C#, VB.NET, and C++.

You would be using this library typically if you are developing for Windows Phone 8 and Windows RT since the Windows PRT API and the Win RT API has a lot of shared codes.clip_image006

So, it is mostly a matter of choice which class you choose since equivalent classes exist in both the APIs

.NET API

Windows Phone Runtime API

System.IO.IsolatedStorage

Windows.Storage

System.NET.Sockets

Windows.Networking.Sockets

System.Threading.ThreadPool

Windows.System.Threading.ThreadPool

Microsoft.Devices.Sensors

Windows.Devices.Sensors

System.Device.Location

Windows.Devices.GeoLocation

Just to let you know, unlike Windows 8HTML/JS app development isn’t possible for WP 8.But we can use HTML 5 hosted in webview to make cross platform apps.

Best Alarm Apps in Windows Store.


Windows store like the android app store is populated by a lot of junk apps that don’t work. For the past few days, I was searching for a decent alarm application and I found that very few of the alarm application actually work. The main problem is that the alarm apps stop running the moment you visit another app.

So here I am going to document the best Alarm Apps in Windows 8 and the various pros and cons.

1. Smart Metro Alarm

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Snoozing, repeating and alarms that repeat on specific days are supported

3. Night Mode to be used as a night stand clock.

4. Stopwatch that works even if the app is closed.

5. Snapped View works properly.

Pros: All the above features actually work. I have bought this alarm and the developer keeps updating this app every week. Alarms ring properly and stopwatch works fine. .The biggest feature is that the alarms actually work even if the lock screen is on or the app isn’t running.

Cons: Overtly simplistic UI.UI could be improved

Rating 8/10

Link

2. Sunrise Clock

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Night mode.

3. Choice of 5 beautiful background picture.

4. Very attractive UI

5. Works in snapped mode.

Pros: Very nice UI. Has the concept of sunrise, so if you keep the alarm app on and go to sleep it will simulate a sunrise with time but, if you are like me you will be too sleepy to notice. Over all the app works great as long as you keep it open. You can choose from 5 different sounds

Cons: The app doesn’t work, when the lock screen is on or you are seeing another app. The alarm unfortunately doesn’t ring when any other app is open. So if you by chance fall asleep without opening the app then your alarms won’t ring. A very serious problem. And also no option of snoozing.

Rating 5/10

Link

3. HD Alarm Clock

A bit pricey alarm clock with heavily customizable features.

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Choose your own alarm tone.

3. Very nice UI

4. Obstacles for deep sleeper.

5. News are shown in one screen.

6. Beautiful themes and work well.

Pros: All the features work as expected. One cool thing is obstacles that are put in place during an alarm

Con: The alarm stops working if the app isn’t running or the lock screen is on. The only problem that seriously impairs the functionality.

Rating: 7/10

Overall winner: Metro Smart Alarm

Exception Handling in Task Based Parallel programming.


As you had learnt in the previous posts, Tasks are executed asynchronously and parallel. Now what happens when there is an exception? How and where is it thrown?

This blog post answers all the above questions

1. What happens when an exception occurs?

When a task causes an exception, it first terminates the Task .E is caught,saved as a part of an AggregateException ae and stored in object’s Exception property

.Now, we know, that I synchronous programming, the exception propagates upward to the caller from the callee.

But in synchronous programming, the scenario is different. Here if the exception is unhandled, it is re thrown at a later time.

2. What do you mean by ‘Later Time’?

The exception AE is rethrown when it encounters .result,.Wait or WaitAll Task functions.The exception if not handled or touched, is rethrown when the task object is garbage collected.

3. What is the proper way to handle exceptions ?

   1: Task<int> T_1 = Task<int>.Factory.StartNew(() => { 

   2:                 //throw new ArithmeticException();

   3:                 //do something awesome that generates an exception

   4:                 return 1;

   5:             });

   6:             try

   7:             {

   8:  

   9:                     int a=    T_1.Result;

  10:             }

  11:             catch (AggregateException AE)

  12:             {

  13:                 AE = AE.Flatten();

  14:                 foreach (Exception ae in AE.InnerExceptions)

  15:                 {

  16:                     //handle each Exception ae

  17:                 }

  18:  

  19:             }

4. What is AggregateException ?

.NET throws all the exception wrapped in a single Exception called Aggregate Exception. Now as we know, that each task can create many subtasks, which again can lead to exceptions. So an aggregate Exception returned by a task, contains all the exception returned by the subtasks.

Consider this scenario, Task A creates Task B and Task C, and in doing so Task A is considered the parent of both Task B and Task C. These relationships come into play primarily in regard to lifetimes. A Task isn’t considered completed until all its children have completed, so if you used Wait on Task A, that instance of Wait wouldn’t return until both B and C had also completed.  So what happens if both throws an exception. Then both the exceptions are wrapped in an aggregate Exception and rethrown.

5 .How do we access the individual exceptions ?

We access it through the Aggregrate Exceptions class. But it might happen that the child of the parent’s task, spawns more child tasks which throws exception. Hence we can see a tree forming,whose leaves are exceptions.

By default, AggregateExceptions retains this hierarchical structure, which can be helpful when debugging because the hierarchical structure of the contained aggregates will likely correspond to the structure of the code that threw those exceptions. However, this can also make aggregates more difficult to work with in some cases. To account for that, the Flatten method removes the layers of contained aggregates by creating a new AggregateException that contains the non-AggregateExceptions from the whole hierarchy.

6. What is observing Exceptions ?

Now, as we said unhandled Exceptions will be rethrown during garbage collection. To avoid that ,there are 4 methods you can “observe” the exceptions or in other words allow the exceptions to be rethrown so that you can handle it.

Calling .Wait, .Result or .WaitAll on tasks will allow the task to re throw the exceptions. [task.waitany does not throw any exceptions)

Access tasks’ Exception property after completion of task.

Subscribe to TaskScheduler.UnobservedTaskException

Accessing the exception property after completion of the task will not re throw the exception. If the exception property is not null, then you would know that an exception was generated. Even if you don’t handle it, the compiler won’t rethrow during garbage collection as you have observed the exception

Difference between continuewhenAll and WaitAll


This is a part of the blog series , “Asynchronous Programming Using DotNet” .Please visit this page to see the “index” of all the posts I wrote on this series.

So what exactly is the difference between continuewhenAll and WaitAll method ? When and where should you use them?

Consider the following piece of code

   1: int start = Environment.TickCount;

   2:

   3: Task T1 = Task.Factory.StartNew(() =>

   4:

   5: {

   6:

   7: Thread.Sleep(3000);

   8:

   9: });

  10:

  11: Task T2 = Task.Factory.StartNew(() =>

  12:

  13: {

  14:

  15: Thread.Sleep(3000);

  16:

  17: });

  18:

  19: Task T3 = Task.Factory.StartNew(() =>

  20:

  21: {

  22:

  23: Thread.Sleep(3000);

  24:

  25: });

  26:

  27: Task[] T_Arr = { T1, T2,T3 };

  28:

  29: Task.WaitAll(T_Arr);

  30:

  31: int stop = Environment.TickCount;

  32:

  33: textBox1.Text =( stop - start).ToString();

The time of run is a little over 3000 miliseconds.

clip_image002

As you can see, Task.waitAll takes an array as an argument and waits till all the tasks are complete. The tasks itself are asynchronous in nature. So the period of waiting is roughly equal to the maximum of (Time taken by T1, Time Taken by T2, and Time Taken by T3).During the waiting period the UI freezes ,as the UI thread is busy waiting!! So basically even though the tasks are done asynchronously, the waiting is synchronous.

So what is the solution ?

The new code is

   1: TaskFactory tf = new TaskFactory();

   2:

   3: tf.ContinueWhenAll(T_Arr, (a) =>

   4:

   5: {

   6:

   7: int stop = Environment.TickCount;

   8:

   9: textBox1.Text = (stop - start).ToString();

  10:

  11: }, new CancellationToken(), TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Continuewhen all typically starts a new thread.Continuewhenall delegate will be called once the tasks are finished and the contents of the continuewhen all will run on a new thread.So there is synchronous waiting.Here in our case ,since we are updating the UI, the task will run on the UI thread,but while waiting for the output it won’t be blocking the UI thread, Hence your application remains responsive, even if your tasks are not complete.