Scott Hanselman

The Magic of using Asynchronous Methods in ASP.NET 4.5 plus an important gotcha

August 29, '13 Comments [35] Posted in ASP.NET
Sponsored By

First, I encourage you to listen to episode 327 of the Hanselminutes podcast. We called it "Everything .NET programmers know about Asynchronous Programming is wrong" and I learned a lot. I promise you will too.

Often we'll find ourselves doing three or four things on one page, loading stuff from a number of places. Perhaps you're loading something from disk, calling a web service, and calling a database.

You can do those things in order, synchronously, as is typical. Add up the duration of each Task:

public void Page_Load(object sender, EventArgs e)
{
var clientcontacts = Client.DownloadString("api/contacts");
var clienttemperature = Client.DownloadString("api/temperature");
var clientlocation = Client.DownloadString("api/location");


var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(clientcontacts);
var location = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(clientlocation);
var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(clienttemperature);

listcontacts.DataSource = contacts;
listcontacts.DataBind();
Temparature.Text = temperature;
Location.Text = location;
}

Each of this three calls takes about a second, so the total type is 3 seconds. They happen one after the other.

Intuitively you may want to make these async by marking the public void Page_Load with async and then awaiting three tasks.

However, Page_Load is a page lifecycle event, and it's a void event handler. Damian Edwards from the ASP.NET team says:

Async void event handlers in web forms are only supported on certain events, as you've found, but are really only intended for simplistic tasks. We recommend using PageAsyncTask for any async work of any real complexity.

Levi, also from the ASP.NET team uses even stronger language. Basically, DO NOT use async on void event handlers like this, it's not worth it.

Async events in web applications are inherently strange beasts. Async void is meant for a fire and forget programming model. This works in Windows UI applications since the application sticks around until the OS kills it, so whenever the async callback runs there is guaranteed to be a UI thread that it can interact with. In web applications, this model falls apart since requests are by definition transient. If the async callback happens to run after the request has finished, there is no guarantee that the data structures the callback needs to interact with are still in a good state. Thus why fire and forget (and async void) is inherently a bad idea in web applications.

That said, we do crazy gymnastics to try to make very simple things like Page_Load work, but the code to support this is extremely complicated and not well-tested for anything beyond basic scenarios. So if you need reliability I’d stick with RegisterAsyncTask.

Using async with voids is not stable or reliable. However, all you have to do is call Page.RegisterAyncTask - it's not any trouble and you'll be in a better more flexible place.

public void Page_Load(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}

public async Task LoadSomeData()
{

var clientcontacts = Client.DownloadStringTaskAsync("api/contacts");
var clienttemperature = Client.DownloadStringTaskAsync("api/temperature");
var clientlocation = Client.DownloadStringTaskAsync("api/location");

await Task.WhenAll(clientcontacts, clienttemperature, clientlocation);

var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(await clientcontacts);
var location = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clientlocation);
var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clienttemperature);

listcontacts.DataSource = contacts;
listcontacts.DataBind();
Temparature.Text = temperature;
Location.Text = location;
}

You can simplify this even more by removing the (in this case totally unnecessary) Task.WhenAll and just awaiting the result of the Tasks one by one. By the time Task.WhenAll  has happened here, the tasks are already back. The result is the same. This also has the benefit of reading like synchronous code while giving the benefits of async.

public async Task LoadSomeData()
{

var clientcontacts = Client.DownloadStringTaskAsync("api/contacts");
var clienttemperature = Client.DownloadStringTaskAsync("api/temperature");
var clientlocation = Client.DownloadStringTaskAsync("api/location");

var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(await clientcontacts);
var location = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clientlocation);
var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clienttemperature);

listcontacts.DataSource = contacts;
listcontacts.DataBind();
Temparature.Text = temperature;
Location.Text = location;
}

This now takes just a hair over a second, because the three async tasks are happening concurrently. Async stuff like this is most useful (and most obvious) when you have multiple tasks that don't depend on one another.

Do remember to mark the .aspx page as Async="true" like this:

<%@ Page Title="Async" Language="C#" CodeBehind="Async.aspx.cs" Inherits="Whatever" Async="true" %>

Related Links


Sponsor: A huge thank you to my friends at Red Gate for their support of the site this week. Check out Deployment Manager! Easy release management - Deploy your .NET apps, services and SQL Server databases in a single, repeatable process with Red Gate’s Deployment Manager. There’s a free Starter edition, so get started now!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

A Cloud and Azure Glossary for the Confused

August 26, '13 Comments [10] Posted in Azure
Sponsored By
Cloud by Karen Ka Ying Wong used under CC via Flicker

A parody Twitter account called Confused .NET Dev last week tweeted:

A "crazy" learning curve? CDN? Table? Drive? OK, if you say so, but still, point taken, there's maybe some terms in there that may not be immediately obvious. Here's a few things you should remember when developing for the cloud as well as a small glossary that I hope helps this "confused .net dev" and his or her mixed case Twitter account.

Cloud Concepts

IAAS

Infrastructure as a Service. This means I want the computers in my closet to go away. All that infrastructure, the boxes, network switches, even software licenses are a maintenance headache. I want to put them somewhere where I can't see them (we'll call it, The Cloud) and I'll pay pennies per hour. Worst case, it costs me about the same but it's less trouble. Best case, it can scale (get bigger) if my company gets popular and the whole thing will cost less than it does now.

IAAS is Infrastructure like Virtual Machines, Networking and Storage in the cloud. Software you wrote that runs locally now will run the same up there. If you want to scale it, you'll usually scale up.

PAAS

Platform as a Service. This means Web Servers and Web Frameworks in the cloud, SQL Servers in the cloud, and more. If you like Ruby on Rails, for example, you might write software against Engine Yard's platform and run it on Azure. Or you might write iOS apps and have them talk to back end Mobile Services. Those services are your platform and will scale as you grow. Platform as a service usually hides the underlying OS from you. Lower level infrastructure and networking, load balancing and some aspects of security is abstracted away.

SAAS

Software as a Service. Like Office 365, SharePoint, Google Docs or Adobe Creative Cloud, you pay a subscription and you always get the latest and greatest.

Scale Up

Get more CPUs, more memory, more power. Same computer, but bigger. Like, one 8-processor machine with 128 gigs of RAM, big. Gulliver.

Scale Out

More computers, perhaps lots of them. Maybe eight 1-processor machine with 2 gigs of RAM. No, maybe 32. More little machines, like Lilliputians working as a team to move Gulliver.

Compute

If a computer is working for you, its CPU is working and that's compute. If it's a Virtual Machine or a Web Server it doesn't matter. You get charged pennies per hour, more for larger CPUs.

IOPs

Input/Output Operations Per Second, pronounced "eye-ops." This is unit of measurement used to describe the maximum number of reads and writes to a disk or storage area.

Queue

Just like a Queue in computer science, it's a holding place that lets you store messages and read them back asynchronously.

Content Delivery Network (CDN)

Taking binary blobs within storage and caching them nearest where the content is request. If your customers are in Asia, serve the file from a data center in Asia.

Azure Specific Glossary

Web Sites

Web Sites are "PAAS," that's platform as a service. It's the IIS Web Server in the sky. This is the "Easy Button" as Jon Galloway says. You can take virtually any website and move them up to Azure using Azure Web Sites. You can run ASP.NET, PHP, node.js and lots more.

Azure Table vs SQL Azure

Azure Tables are similar to a document database or NoSQL store. Then there's SQL Azure, which is SQL Server in the sky. Great for SQL-like data with relationships and indexes, etc. There's Azure Storage Tables which is nice when you have a huge pile of records that maybe doesn't have a lot of interrelationships, but there's a LOT of it.

Access Control

Controls Access. Just kidding. No, actually I'm not. Also know as ACS, it's a hosted service that integrates with Microsoft ID, Google, Facebook, Yahoo and other identity providers as well as Active Directory. It supports .NET, PHP, Python, Java, Ruby, etc and you can use it as a centralized authorization store. You can call it with web services from any app and manage users and identities from the portal.

Notification Hubs

Push notification services for any mobile platform. Windows Store, Windows Phone, iOS and Android. Broadcast messages to a user across apps or send single notifications to a user,  a platform or any combination.

AppFabric Caching

In memory caching for apps that run on Azure. You can use existing memory on web roles or dedicate all of a worker roles memory to in-memory caching.

Mobile Services

This is a complete Backend in a Box for apps. This isn’t a great name because it’s not just for mobile devices. It’s a complete backend-as-a-service including authentication and CRUD data access with a dynamic schema in the backend. The services are server-side JavaScript and totally managed for you. Supports iOS, HTML, Windows Phone, Win8, Android, and more. 

Media Service

Media squishing and delivery in the cloud. Production and transcoding workflow, secure delivery to any device, scale up and down elastically.

Service Bus

Secure messaging across firewalls and NAT gateways. It also offers relayed messaging services. Most large hosted and reliable systems need messaging services, sometimes request/response, sometimes peer-to-peer, and sometimes one-way.

X-Plat CLI

An open source JavaScript-written command line tool for Azure management. With node.js and npm installed go "npm install azure-cli --g" and get a complete management console for Azure that runs on Linux, Mac and Windows.

Big Data and HDInsight

Apache Hadoop in the Sky, running on Azure. Hadoop is a giant Java-based MapReduce system for creating data-intensive distributed apps. Azure adds lots to augment with .NET support, LINQ, reporting and more.

Blob

Binary Large Object...it's any binary blob you've put in Azure storage. Throw them in, get them back.

VHD

Virtual Hard Drive. Just like a VHD in Hyper-V or Virtual PC, this binary file represents a complete virtual disk.

Adding more than one disk to a Virtual Machine is a quick and easy way to get more speed for free. For example, if you've got a Virtual Machine running Windows AND a Database like MySQL, you'll have the database application and the Operating System competing for the maximum number of IOPs supported by the disk. Instead, make a new disk and mount it, putting the database on its own drive. This way you've doubled your IOPs with the OS on one drive and the database gets the maximum from its down drive.

Drive

You can mount an single Azure VHD as a disk drive within a Virtual Machine or you can mount Blob Storage as a virtual drive of its own.

Related Links

Did I miss anything major? I'm sure I did, but I wanted to show folks that it's a glossary, sure, but it's not rocket surgery.


Sponsor: A huge thank you to my friends at Red Gate for their support of the site this week. Check out Deployment Manager! Easy release management - Deploy your .NET apps, services and SQL Server databases in a single, repeatable process with Red Gate’s Deployment Manager. There’s a free Starter edition, so get started now!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Hanselman's Newsletter of Wonderful Things: August 5th, 2013

August 26, '13 Comments [5] Posted in Newsletter
Sponsored By

I have a "whenever I get around to doing it" Newsletter of Wonderful Things. Why a newsletter? I dunno. It seems more personal somehow. You can view all the previous newsletters here.

Here's the newsletter that I sent out August 5th. You can sign up here to the Newsletter of Wonderful Things or just wait and get them weeks later on the blog, which hopefully you have subscribed to. Subscribers get the goodness first!


Hi Interfriends,

Thanks again for signing up for this experiment. Here's some interesting things I've come upon this week. If you forwarded this (or if it was forwarded to you) a reminder: You can sign up at http://hanselman.com/newsletter and the archive of all previous Newsletters is here.

Remember, you get the newsletter here first. This one will be posted to the blog as an archive in a few weeks.

Scott Hanselman

(BTW, since you *love* email you can subscribe to my blog via email here: http://feeds.hanselman.com/ScottHanselman DO IT!)

P.P.S. You know you can forward this to your friends, right?


Sponsor: A huge thank you to my friends at Red Gate for their support of the site this week. Check out Deployment Manager! Easy release management - Deploy your .NET apps, services and SQL Server databases in a single, repeatable process with Red Gate’s Deployment Manager. There’s a free Starter edition, so get started now!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Am I really a developer or just a good googler?

August 23, '13 Comments [98] Posted in Musings
Sponsored By
Photo by Hugh Ryan McDonald used with CC Attribution

I got a very earnest and well-phrased email from a young person overseas recently.

Some time in my mind sounds come that Is that I am really a developer or just a good googler. I don't know what is the answer I am googler or I am developer. Scott Please clear on my mind on this please.

This is a really profound question that deserved an answer. Since I only have so many keystrokes left in my life, I am blogging my thoughts and emailing a link.

I've felt the same way sometimes when playing a video game. It'll get hard as I progress through the levels, but not crushingly hard. Each level I squeak by I'll find myself asking, "did I deserve to pass that level? I'm not sure I could do it again."

You get that feeling like you're in over your head, but just a bit. Just enough that you can feel the water getting into your nose but you're not drowning yet.

First, remember you are not alone. I think that we grow when we are outside our comfort zone. If it's not breaking you down, it's not building you up.

Second, anything that you want to be good at is worth practicing. Do Code Katas. Do a Project Euler problem every few weeks, if not weekly.

Third, try programming for a day without Googling. Then two days, maybe a week. See how it feels. Remember that there was a time we programmed without copying our work.

Fourth, think about the problem, deeply. Read about algorithms, read Programming Pearls, read about Design Patterns. Rather than copying code from Stack Overflow, copy patterns from the greats.

Fifth, get involved. Go to User Groups, Nerd Dinners, meet with others who feel the same way you do about technology. Stretch.

What do you think?


Sponsor: A big thanks and a warm welcome to Aspose for sponsoring the feed this week! Check out their Aspose.Total for .NET has all the APIs you need to create, manipulate and convert Microsoft Office documents and a host of other file formats in your applications. Curious? Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Google Chromecast Review - The race is on to wirelessly throw video to your TV

August 23, '13 Comments [29] Posted in Reviews
Sponsored By

Google ChromecastThe Google Chromecast is simple and brilliant. It's one of those perfect little "duh! Why didn't someone do that before?" ideas.

I didn't realize I needed one until I realized that I've been chasing the idea for years. In fact, I put together a poor man's "AirPlay Raspberry Pi" Chromecast last year. By plugging my Raspberry Pi running RaspBMC into my Receiver and using it just for Airplay, I was effectively using it as a Chromecast.

You can agree or disagree in the comments, but here's their idea - most of us don't need set-top boxes. The world's big technology companies clearly want to control the largest screen in the house. So far, that's the TV (if you own one.) If TVs go away, it'll be the largest monitor in the house. What's the best way to control this screen?

  • You can get a PS3 or an Xbox. (I have both.)
  • You can get a TiVo. (check.)
  • You can get an Apple TV. (I did the XBMC Airplay thing instead.)

But each of these devices is a darn-near full computer with an OS, and storage, and a life and ecosystem of its own. What we really want is to use our TVs as wireless displays and use the power of our phones, tablets, and computers. Until one of the world's wireless display formats is finally declared the winner, they'll keep making set-top boxes portable computers to connect to our TVs.

We could wait for $1000 receivers to include Wireless Display functionality, or build it into HDTVs. No! Let's make a $35 dongle that capitalizes on the fact that HDMI has finally won. It'll plug into any monitor and we suddenly that HDMI connection is available over wireless. It's open, in fact, to anyone who is on the network.

You just plug the Chromecast into any free HDMI port and get power via micro-USB. Many TVs have a USB port that can provide this power. I used the always-on USB port from my TiVo as it was open.

The Chromecast contains the Marvell 88DE3005 system on a chip. This integrated circuit includes hardware decoding of VP8 and H.264 codecs. Radio communication is handled by AzureWave NH–387 Wi-Fi which supports 802.11b/g/n (2.4 GHz). The device has 512 MB of Micron DDR3L RAM and 2 GB of flash storage. - Wikipedia

When you plug the Chromecast into your TV you'll connect to its initial ad-hoc wireless network and teach it about your wireless network. Then it'll reboot and jump sideways onto your network and most of your config work is done. The only way to change the Chromecast at this point is to hard reset it. The wireless setup process is very similar to other embedded wireless devices like the Nest Thermostat, FitBit Aria Scale, or Twine Wi-Fi device - connect to ad-hoc, setup locally, jump. It took all of 2 minutes.

Ready to cast

Here's my Chromecast plugged into my Onkyo TX-SR674 Receiver's front HDMI port.

The Chromecast in my Receiever

Make sure your phone's YouTube and Netflix apps are updated. They all got Chromecast support automatically last month.

From inside the Google Chrome browser you add the Google Cast extension that lets you play content from within Chrome to the Chromecast. You can cast a browser tab to the screen and show a friend what you're browsing, which is actually very cool and useful...when it works. More on that in a second.

The Good

When it works, it's fabulous. For example, at a recent party someone mentioned a funny YouTube video. Within 30 seconds I had it up on my iPhone, then threw it to the Chromecast. That's exactly how it should work, right?

YouTube Casting Netflix Chromecasting

I've thrown video to the Chromecast from all my iDevices in both the Netflix and YouTube apps. There is a hand-off and then, interestingly, the Chromecast takes over the stream. Rather than the phone or tablet pulling the content down then pushing it again laterally to the Chromecast, there's a little YouTube applet or NetFlix applet running on the Chromecast. The Chromecast inherits or hijacks the stream. All of this is transparent to the user, of course, but it's a clever implementation which allows you to close the app and do other things with your phone.

Each app looks a little different. The YouTube iPhone app shows Views, avatars, and the date when pushed to the Chromecast.

YouTube on a Chromecast

Being able to use your Tablet as a remote is great. Myself, I get this functionality in three totally different ways across my devices, but the result is the same - tablets are good remotes. I have the Tivo App on my iPad, I have the Xbox Smartglass app on my iPad and Surface, and I have the YouTube and Netflix apps on my iPad talking to the Chromecast.

HDMI-CEC is the ability for the Chromecast to automatically tell my receiver to switch to the right HDMI input when content starts playing. It would be amazing if my receiver supported it. If your system has HDMI-CEC the Chromecast will set your inputs for you and remove a step which has a high WAF (Wife Acceptance Factor or Non-Gender-Specific Spouse Acceptance Factor).

The Bad

My computers just can't see the Chromecast anymore. They could last week. This is extremely odd considering we are all on the same wireless network and that the phones and tablets work reliably. You'll find the forums filled with people fighting with this issue. They're having to disable firewalls on MacBooks and turn off IGMP Proxies on FIOs Routers. I've done all that and while on the first day my first laptop was able to cast its Chrome Tabs to the TV, a few days later either Chrome or the Chromecast auto-updated itself and now it's just dead.

No cast devices found

No matter, for $35 it's a great device. It works as advertised on both iPhone, iPad and Android, although the settings for casting from iPhones are a little inconsistent and hard to find in Netflix and YouTube. The Chromecast troubleshooting should be more polished (today it's just a link to a FAQ, with no diagnostics) but since Chrome and the Chromecast both appear to be updating quite often, we should see improvements soon. If I had paid $80 or more, I would be more frustrated with my inability to use the device from my desktop and laptops, but the tablets and phones have been rock solid.

I'd love to see the Chromecast become a more generic wireless receiver and be extended to support Apple's Airplay, as well as Miracast which is now built into Windows 8.1, and WiDi that Intel supports (although Wi-Di also supports Miracast as of WiDi 3.5). Unfortunately though, here we are again with FOUR companies each betting on a format to win while the consumer is left to pick a horse.

Which wireless display format will become Bluray and which will become HD-DVD? It's anyone's guess. I'd like to see an open format win. However, for now, and for only $35, I'm happy with the Chromecast.


Sponsor: A big thanks and a warm welcome to Aspose for sponsoring the feed this week! Check out their Aspose.Total for .NET has all the APIs you need to create, manipulate and convert Microsoft Office documents and a host of other file formats in your applications. Curious? Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.