Presentation Materials for Boston Code Camp 19

Thanks to everyone for coming!

A Survey of Multi-threading in .NET 4.5: Slides | Sample Code for all 6 libraries | More Samples for Async/Await

Reactive Extensions: http://msdn.microsoft.com/en-us/data/gg577609
TPL Dataflow: http://msdn.microsoft.com/en-us/devlabs/gg585582
Async Targeting Pack: http://www.microsoft.com/en-us/download/details.aspx?id=29576

Async or Asink?

More and more nowadays there is a push  to run more application code in an asynchronous manner to prevent blocking the UI thread and making the application unresponsive.  As the need for this type of programming becomes more prevalent thankfully the APIs to do so have also become easier to implement.  The last part (easier APIs) has led to more and more async code sprinkled through an application like the little candies on top of donuts.  Unfortunately the easier APIs also mean it’s easier to abuse the functionality by not properly implementing exception handling.

All of these async sprinkles can sink an application fast as code may be exploding left and right with the application user non the wiser.  From the users perspective everything seems like it’s ok (i.e. the app doesn’t abort or show error dialogs) but nothing seems to be working.

I’d like to take a moment to look at various ways to async a task and highlight the exception handling issues related to each.  To do this I am going to use the following program framework.  My goal each time is to first see whether an unhandled exception occurs and if so then to handle it appropriately.

	class Program
	{
		static void DoSomething(object state)
		{
			try
			{
				throw new InvalidOperationException();
			}
			catch
			{
				Console.WriteLine("Exception thrown in method DoSomething.");
				throw;
			}
		}

		static void Main(string[] args)
		{
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

			//
			// TODO: Insert async code that calls the method DoSomething
			//

			Console.WriteLine("Done.");
			Console.ReadLine();
		}

		static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Console.WriteLine("Entered UnhandledException handler.");
		}
	}

As I replace the “TODO:” with each type of async code I’ll “Start Without Debugging” in Visual Studio. 

If the program runs WITHOUT encountering an unhandled exception the window will look like the following.  This can happen in two different scenarios.  Either the program encountered an unhandled exception but the exception was gobbled up and nobody will ever know or we have implemented proper exception handling code to deal with the exception when it occurs.

image

If the program encounters an unhandled exception then the window will look something like the following in which the task will then be to implement proper exception handling code.

image

Background Thread Exception Behavior

Before we start into the meat of this article it’s important to note both the .NET Framework version and the existence of a specific configuration setting can change the behavior of an application when an exception occurs on a background thread.  For more information on this topic see http://msdn.microsoft.com/en-us/library/ms228965.aspx.

Briefly .NET 1.0 and .NET 1.1 allowed background threads to throw unhandled exceptions that WOULD NOT terminate the application.  The .NET Framework would terminate the thread itself but the application would be unaffected and more than likely the unhandled exception would go unnoticed.

For all other .NET Framework version this behavior can be reinstated (BAD IDEA!) using the application configuration setting:

	<configuration>
		<runtime>
			<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
			<legacyunhandledexceptionpolicy enabled="1" />
		</runtime>
	</configuration>

All of the code we use following this WILL NOT have the configuration setting enabled and will be using .NET 4.5.  That being said it very easy to get the same behavior without using the configuration setting on a newer .NET Framework version.  In fact it sometimes seems like this old style is still in effect.

System.Threading.Thread

Our first attempt will be to use the System.Threading.Thread object.  We’ll replace the // TODO: line with the code:

	// 1. Thread.Start
	Thread thread = new Thread(new ParameterizedThreadStart(DoSomething)) { IsBackground = false };
	thread.Start();

When this code is executed we see that an unhandled exception occurs.  Note that I set the IsBackground property to false. 

If this is set to true then no unhandled exception occurs.  What’s up with this?  I thought .NET Framework 2.0 and above didn’t swallow exceptions anymore?  Even though “technically” the .NET Framework does not swallow exceptions anymore, “effectively” it does UNLESS you go back at some point and “sync up” with the thread.  When using System.Threading.Thread this is done via a call to the Join method on the thread.  So if we modify the code to:

	// 1. Thread.Start
	Thread thread = new Thread(new ParameterizedThreadStart(DoSomething)) { IsBackground = false };
	thread.Start();
	thread.Join();

we see the proper behavior (that an unhandled exception occurs) whether the thread is a background thread or not.  When using this method to async something the only way to properly handle the exception is in the try/catch block in the DoSomething method.  Putting a try/catch block around the thread.Join() method does nothing even though with other async APIs that pattern works as we’ll see later.

delegate BeginInvoke/EndInvoke

The next attempt to async the DoSomething method will use the delegate async architecture.  A delegate provides the methods Invoke(), BeginInvoke() and EndInvoke().  Using the Invoke() method would be the equivalent of just calling the DoSomething method without any async wrapping.  A call to BeginInvoke() is what will cause the DoSomething method to run asynchronously.  To run this code replace the // TODO: line with the code:

	// 2. BeginInvoke/EndInvoke
	Action action = DoSomething;
	action.BeginInvoke(null, null, null);

We’re back to not seeing an unhandled exception.  We receive the message “Exception thrown in method DoSomething.” but that’s it.  No unhandled exception.  Just like with System.Threading.Thread we have to “sync up” with the thread at some point in order for the unhandled exception to be properly generated:

	// 2. BeginInvoke/EndInvoke
	Action action = DoSomething;
	action.BeginInvoke(null, action.EndInvoke, null);

and to properly handle the exception we can use the same method as with System.Threading.Thread and modify the catch block in the DoSomething method or we can use a try/catch block around the EndInvoke() like so:

	// 2. BeginInvoke/EndInvoke
	Action action = DoSomething;
	action.BeginInvoke(
		null,
		result =>
			{
				try
				{
					action.EndInvoke(result);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Exception handled.");
				}
			},
		null);

Note that adding a Console.WriteLine() to the catch block isn’t REALLY properly handling the exception.  It’s just simulating proper handling code which would more than likely log the exception, possibly correct it and maybe even let it continue to percolate up the stack by using a throw; statement.

System.Threading.ThreadPool.QueueUserWorkItem

The next attempt to async the DoSomething method will specifically use the ThreadPool.  Some of the later methods use the ThreadPool implicitly but here we will do so explicitly.  To run this code replace the // TODO: line with the code:

	// 3. ThreadPool.QueueUserWorkItem
	ThreadPool.QueueUserWorkItem(DoSomething, null);

It’s refreshing to see that we don’t actually have to do any “sync up” with the thread.  And realistically you couldn’t even do it.  Regardless we find that in this specific instance the unhandled exception is properly generated.

To properly handle the exception we can use a method similar to that used with BeginInvoke/EndInvoke:

	// 3. ThreadPool.QueueUserWorkItem
	ThreadPool.QueueUserWorkItem(
		state =>
			{
				try
				{
					DoSomething(state);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Exception handled.");
				}
			},
		null);

System.ComponentModel.BackgroundWorker

The next attempt to async the DoSomething method will use the BackgroundWorker class.  To run this code replace the // TODO: line with the code:

	// 4. BackgroundWorker
	BackgroundWorker worker =
		new BackgroundWorker();
	worker.DoWork += (sender, e) => DoSomething(e);
	worker.RunWorkerCompleted += (sender, e) => worker.Dispose();
	worker.RunWorkerAsync();

We find once again that in this initial case the unhandled exception is not properly generated.  With the BackgroundWorker there is no way to “sync up” without using things like status checking loops or ManualResetEvent.  We can however add code to properly handle the exception.

	// 4. BackgroundWorker
	BackgroundWorker worker =
		new BackgroundWorker();
	worker.DoWork += (sender, e) => DoSomething(e);
	worker.RunWorkerCompleted +=
		(sender, e) =>
			{
				if (e.Error != null)
				{
					Console.WriteLine("Exception handled.");
				}

				worker.Dispose();
			};
	worker.RunWorkerAsync();

System.Threading.Tasks.Task

The next attempt to async the DoSomething method will use the .NET 4 Task.  To run this code replace the // TODO: line with the code:

	// 5. Task.Factory.StartNew
	Task.Factory.StartNew(DoSomething, null);

Lately I’ve been finding that this is the most common pattern that somebody will use to async a method.  Most likely because it’s cool and it’s easy.  This particular pattern is why I wrote this article.  The problem is that this pattern, like the others, will allow the method called to throw an exception and the application code will be none the wiser.  Imagine 10, 20, 50, 100s of these spread throughout the code base all randomly aborting and the user is wondering why things don’t seem to work even though they see no obvious signs of problems, i.e. exceptions or error dialogs.

If we modify this code to “sync up” with the thread like so:

	// 5. Task.Factory.StartNew
	Task task = Task.Factory.StartNew(DoSomething, null);
	task.Wait();

We find that the unhandled exception is properly generated, however the task.Wait() like the thread.Join() kind of defeat the purpose of attempting to run the DoSomething method asynchronously.  To solve this problem use task chaining:

	Task.Factory
	    .StartNew(DoSomething, null)
	    .ContinueWith(
		    task =>
			    {
				    try
				    {
					    task.Wait();

					    // If the DoSomething method returned a result
					    // we could reference task.Result instead to
					    // trigger the exception if one occurred otherwise
					    // process the result.
				    }
				    catch (AggregateException ae)
				    {
					    ae.Handle(
							(ex) =>
								{
									Console.WriteLine("Exception Handled.");
									return true;
								});
				    }
			    });

In our case the DoSomething method is of type Action<object> and not Func<object, TResult>, i.e. it doesn’t return a result.  If the DoSomething method returned a result we could reference task.Result instead of using task.Wait() to “sync up” with the task and trigger the exception.  In this code we use the AggregateException.Handle method to handle the exceptions.  The .NET 4 task returns exceptions of type AggregateException.  How these differ from System.Exception is that they have an InnerExceptions (note that it’s plural) property as well as the inherited InnerException property.  An AggregateException can contain multiple exceptions (one from each task that was chained) and the AggregateException.Handle method will call the specified delegate for each of those exceptions.

Since the DoSomething method doesn’t return a result there is nothing to process after it’s done so we can tell the .ContinueWith task to only execute if a fault occurred like so:

	// 5. Task.Factory.StartNew
	Task.Factory
	    .StartNew(DoSomething, null)
	    .ContinueWith(
		    task =>
			    {
					try
					{
						task.Wait();
					}
					catch (AggregateException ae)
					{
						ae.Handle(
							(ex) =>
							{
								Console.WriteLine("Exception Handled.");
								return true;
							});
					}
			    },
		    TaskContinuationOptions.OnlyOnFaulted);

Session 4 of the WinRT Development Class – Async/Await, WinRT API, and Security

Thank you all for attending Session 4 of our WinRT Development Course. It was great to see you all understand, embrace and use the new WinRT API! J

Session Resources:

  • AsyncDemonstration.zip: Source code of the project I used to demonstrate the difference between synchronous and asynchronous code execution
  • DemoFinal.zip: Source code of the project we developed together. This application allows to take a picture from an attached webcam, save it in the Pictures Library and create diary entries.
  • Presentation.pptx: The slide deck
  • Session Recording
  • HomeworkFinal.zip: Sample implementation of the homework (please try to solve it on your own first!)

Please don’t forget about Danny’s upcoming session on Monday – Jan 28th! I will see you all again on February 4th!

Overview of sessions

The links below lead you to Meetup Events where you can RSVP. We look forward to seeing you at our next session!

1. Introductory Lecture (Nov 27th by Danny & Kevin)
2. Introduction to XAML and WinRT’s powerful Control Framework; (Dec 4th by Danny & Kevin Click here for the video recording)
3. Page-Navigation Model and Application Lifecycle (Jan 8th by Danny Click here for the video recording)
4. Fundamentals (Async/Await, WinRT API, Security) (Jan 15th by Kevin Click here for the video recording)
5. Settings and Search Contract (Jan 28th by Danny)
6. Share Contract (Feb 4th by Kevin)
7. Live Tiles and Background Tasks (March 18th by Kevin)
8. Orientation Handling and Proximity using Near Field Communication (NFC) (March 25th by Danny)
9. Introduction to ModelViewViewModel (MVVM) (April 8th by Danny)
10. InterKnowlogy’s WinRT MVVM Framework Session Part I/II(April 22nd by Kevin)
11. InterKnowlogy’s WinRT MVVM Framework Session Part II/II(May 6th by Danny)
12. Presentation of Hackathon Results + Certificate/Prize Giveaway(May 22nd by Danny and Kevin)

Impressions





Presentation Materials for Boston Code Camp 18

Great event at a new location! I hope everyone enjoyed it.

A Survey of Multi-threading in .NET 4.5: Slides | Code

Future-proofing your XAML Applications with Portable Libraries: Slides | Code

Portable Libraries Hands-On-Lab: http://tinyurl.com/plibhol
Reactive Extensions: http://msdn.microsoft.com/en-us/data/gg577609
TPL Dataflow: http://msdn.microsoft.com/en-us/devlabs/gg585582
Async Targeting Pack: http://www.microsoft.com/en-us/download/details.aspx?id=29576

Presentation Materials for San Diego Code Camp

Thanks to everyone for another great Code Camp!

Future-proofing your XAML Applications with Portable Libraries: Slides | Code

A Survey of Multi-threading in .NET 4.5: Slides | Code

Visual Studio 11: http://www.microsoft.com/visualstudio/11/en-us/downloads

Portable Libraries Hands-On-Lab: http://tinyurl.com/plibhol

Reactive Extensions: http://msdn.microsoft.com/en-us/data/gg577610

Presentation Materials for New England Code Camp 17

Thanks to everyone for coming!

What’s new in Visual Studio 11: Slides | Code
Check the slides for the list of all of the new Visual Studio features we looked at.

Easy Async in .NET 4.5: Slides | Code (for VS11 Beta)
The only code demo we didn’t get to look at can be found in the AddingAsync page, which shows a progression of converting a more complex 2 step data loading process from fully synchronous to fully asynchronous including cancellation and exception handling.

Presentation Materials for NEVB User Group February

Thanks to everyone for coming and all the questions! It was great to get to introduce some more people to Windows 8 along the way too.

Downloads for Previews and CTPs can be found here: http://msdn.microsoft.com/en-us/vstudio/async.aspx

Slides: Async 2012

Async Sample: Demo Code for VS 11 (VB) | Demo Code for VS 11 (C#) | Demo Code for Async CTP in VS 2010 (C#)

Metro Sample: Code for VS 11 (C#) Requires Windows 8 to open in VS

Presentation Materials for Fullerton Code Camp 2012

Additional downloads to try out the demo code:

Download the Visual Studio 11 Developer Preview: http://msdn.microsoft.com/en-US/vstudio/hh127353

Or get the Async CTP for 4.0 and Visual Studio 2010: http://msdn.microsoft.com/en-us/vstudio/async.aspx

Windows 8 Developer Preview for all WinRT/Metro samples: http://msdn.microsoft.com/en-us/windows/apps/br229516

Easy Async with .NET 4.5: Slides

Code: .NET 4.5 Code (requires VS11 Preview) | Same Code for .NET 4 CTP

Windows 8 Metro Code (requires VS 11 on Windows 8 to build)

The Future of XAML: Slides

Code: Sample Metro App (requires VS 11 on Windows 8 to build) | Sample Silverlight 5 App (shows some things that either don’t work or change in Metro)

The Real-Time Web With SignalR

Today for RECESS I looked into SignalR.  The SignalR site (which currently is just the github repository) describes it as an “async signaling library for ASP.NET to help build real-time, multi-user interactive web applications.”  What does this mean to you and me?  This library allows you, in just a few lines of code, communicate in real-time amongst browsers that are hitting your site.

Scott Hanselman does a good job of summarizing what SignalR does and how we got here, so I won’t repeat it here.

I followed the super quick sample – a browser based chat application as described Scott’s post.  I ran out of time before I could get the lower level connection working, but the higher level “Hub” based connection works great.

It’s super cool to see it working – I have 3 different browsers (IE, Chrome, Firefox) in the chat together.  When I enter a chat message in one, the other two receive the message instantaneously.

    $("#broadcast").click(function () {
      // send() is the method on the ASP.NET Hub class running on the server
      chat.send($('#msg').val());
    });

The use of dynamic objects in the ASP.NET implementation of the Hub allows me to call any method on the Hub, as long as that function exists in the client side JavaScript.

    public class Chat : Hub
    {
        public void Send( string message )
        {
            // addMessage is a client side javascript function
            Clients.addMessage(message);  
        }
    }

Here’s a couple shots of IE Developer Tools (F12) when running the chat client.

Waiting for a response on the first call to signalr/connect:

CropperCapture81

Got the response from the first connect (a message was broadcast to all the clients), now turn right around and connect to wait for the next “reply” from the server:

CropperCapture82

 


 

Presentation Materials for NE Code Camp 16

Thanks to everyone for coming!

To try out the code we looked at:

Download the Visual Studio 11 Developer Preview: http://msdn.microsoft.com/en-US/vstudio/hh127353

Or get the CTP for 4.0 and Visual Studio 2010: http://msdn.microsoft.com/en-us/vstudio/async.aspx

Easy Async with .NET 4.5: Slides

Code: .NET 4.5 Code (requires VS11 Preview) | Same Code for .NET 4 CTP

Windows 8 Metro Code (requires VS 11 on Windows 8 to build)