Search This Blog

Loading...

Tuesday, May 15, 2012

The Task: Async and Await in a Windows Runtime World

In my last blog post, I covered how to wrap your arms around the Task class and its relationship to the new async and await keywords. I mentioned that the post was focused on the .NET Framework only because the Windows Runtime handles these operations differently. In this post, I’ll cover what those differences are.

Task is a Task is a Task

First, in the Windows Runtime, a Task is a Task … is a Task. You can write your code to return a Task or Task<T> in your Windows 8 Metro applications. If you are going to expose a Windows Runtime (WinRT) component, however, one of the rules is that you must always return a WinRT type. For asynchronous operations, there are four types allowed:

No Result Returns Results
No Progress or Cancellation IAsyncAction IAsyncOperation<TResult>
Supports Progress and/or Cancellation IAsyncActionWithProgress<TProgress> IAsyncOperationWithProgress<TResult, TProgress>

The type you return depends on whether or not you return a result, and whether or not you support checking progress and/or cancellation.

Task is a IAsyncAction or IAsyncOperation<T>

If you don’t support progress or cancellation, returning the necessary type is easy: simply use a Task and return it using one of the extension methods to convert it to the corresponding WinRT type. For example, the following useless piece of code iterates through all of the available integers and returns nothing:

public static IAsyncAction IterateAsync()
{
   return Task.Run(() =>
   {
      for(int x = Int.MinValue; x < Int.MaxValue; x++) ;
   }).AsAsyncAction();
}

For a more practical example, consider the multiplication method I used in the last blog post. To convert that to a result, I simply do:

public IAsyncOperation<int> Multiply(int a, int b)
{
   return Task.Run(() => a * b)
      .AsAsyncOperation();
}

That’s fairly simple and straightforward. What about supporting progress and/or cancellation?

Forget Tasks: The 411 on AsyncInfo

The AsyncInfo class is there to assist you with performing asynchronous actions or operations that support cancellation and reporting progress.

public static IAsyncOperationWithProgress<int, double> Multiply(int a, int b)
{
   return AsyncInfo.Run<IList<long>, double>((token, progress) =>
      Task.Run<int>(() =>
      {
         progress.Report(0);
         var result = a*b;
         token.ThrowIfCancellationRequested();
         progress.Report(100.0);
         return result;
      }, token));
}

Obviously the operation is a bit contrived as the multiplication operation doesn’t take as long, but hopefully this simple example illustrates the point of what is possible. The IAsyncActionWithProgress will work the same way, it simply doesn’t return a result.

There you have it … the scoop on the new async and await keywords and how they behave both with and without the Windows Runtime. Now that you have the basics, head over to Stephen Toub’s blog post and read the far more in depth Diving Deep with WinRT and await.

Friday, May 11, 2012

The Task: Events, Asynchronous Calls, Async and Await

Almost any software application today will likely contain a long-running process. “Long-running” may be a relative term but in the Windows Runtime it is specifically anything that could take longer than 50ms to execute. That’s a fairly small window, and it means those operations will need to run concurrently to the main application thread. Concurrency is important in both client applications (to keep from blocking the UI) and server applications (to accommodate multiple simultaneous requests).

The new technology referred to as Visual Studio Asynchronous Programming provides a streamlined language syntax for asynchronous development. It does this by providing two new keywords: async and await. While these keywords may simplify asynchronous development, they can still be confusing to developers. There are a lot of materials out there but I thought it might help to take a very simple example and explore just what these keywords are and how they operate. In this post I’ll focus specifically on the .NET Framework 4.5 support. While they are also supported for Metro-style applications, the implementation is slightly different.

The Main Event

In the movie Mission Impossible II, the short-lived protagonist Dr. Nekhorvich says:

“…every search for a hero must begin with something every hero needs, a villain. So in a search for our hero, Bellerophon, we have created a more effective monster: Chimera.”

In the search for an elegant solution to asynchronous programming we must start with some of the rougher implementations that have plagued developers in the past.

The event-based pattern is probably one of the most well-known asynchronous patterns to .NET developers as it is prevalent throughout the base library. Let’s assume I have a method that multiplies two numbers and for some crazy reason (maybe I’m sending it over a 300 baud modem to my Commodore 64 to process the result on the 6502 chip … you know, using a bunch of ROR operations) it takes a bit longer to process than I’d like, so I want to make sure it executes asynchronously. The first thing I’ll do is create an event argument payload for the result:

public class MultiplyEventArgs : EventArgs 
{
    public int Result
    {
        get;
        private set; 
    }

    public MultiplyEventArgs(int result)
    {
        Result = result;
    }
}

Next, I’ll define an interface:

public interface IMultiplierEvent
{
    event EventHandler<MultiplyEventArgs> MultiplyCompleted;
    void MultiplyAsync(int a, int b); 
}

Finally, I’ll implement the class that executes the operation asynchronous and fires the completed event when done.

public class MultiplierEvent : IMultiplierEvent
{

    public event EventHandler<MultiplyEventArgs> MultiplyCompleted;

    private void RaiseCompleted(int result)
    {
          
        var handler = MultiplyCompleted;
        if (handler != null)
        {
            handler(this, new MultiplyEventArgs(result));
        }
    }

    public void MultiplyAsync(int a, int b)
    {
        Task.Run(() => RaiseCompleted(a * b));
    }
}

I can test this in a simple console program with a method call:

class Program
{
    static void Main(string[] args)
    {
        var p = new Program();
            
        p.DoEvent();

        Console.ReadLine();
    }
}

The implementation requires two methods, one to set it up and another to receive the completed event. Not bad, but you can imagine handling a chain of multiple events could get ugly quickly.

public void DoEvent()
{
    Console.WriteLine("Firing as an event 2 * 3 ..."); 
    IMultiplierEvent eventBased = new MultiplierEvent();
    eventBased.MultiplyCompleted += eventBased_MultiplyCompleted;
    eventBased.MultiplyAsync(2, 3);
}

void eventBased_MultiplyCompleted(object sender, MultiplyEventArgs e)
{
    Console.WriteLine("Event result: {0}", e.Result); 
}

That’s the old world of events.

The Asynchronous Programming Model

Another popular asynchronous model is the Asynchronous Programming Model, or APM. The framework provides the IAsyncResult interface and you specify a pair of methods to Begin and End the operation. The first method always returns the IAsyncResult and the second method always takes the IAsyncResult and returns the result of the call.

In the implementation I create a nested class used to help maintain the state between the calls:

private class AsyncState
{
    public Delegate MethodToCall { get; private set; }
    public object State { get; private set; }

    public AsyncState(Delegate methodToCall, object state)
    {
        MethodToCall = methodToCall;
        State = state;
    }
}

Then I implement the methods. Notice that I’m casting the method call to a delegate and taking advantage of the built-in capability to invoke it asynchronously, then wrapping the end call to return the result.

public class MultiplierApm : IMultiplierApm
{
    private class AsyncState [...]

    public IAsyncResult BeginMultiply(int a, int b, AsyncCallback callback, object state)
    {
        Func<int, int, int> multiply = Multiply;
        var asyncState = new AsyncState(multiply, state);
        return multiply.BeginInvoke(a, b, callback, asyncState); 
    }

    public int EndMultiply(IAsyncResult asyncResult)
    {
        var asyncState = (AsyncState)asyncResult.AsyncState;
        var multiply = (Func<int, int, int>)asyncState.MethodToCall;
        return multiply.EndInvoke(asyncResult); 
    }

    public int Multiply(int a, int b)
    {
        return a * b;
    }
}

Now that I have an implementation, I can call it like this:

public void DoApm()
{
    Console.WriteLine("Firing as APM 3 * 4 ..."); 
    IMultiplierApm apmBased = new MultiplierApm();
    apmBased.BeginMultiply(3, 4,
        result =>
        {
            var value = apmBased.EndMultiply(result);
            Console.WriteLine("Apm result: {0}", value);
        }, null);
}

Note that I might have used two methods for the APM as well, I simplify chose to take a short cut but using a lambda expression instead.

Taking Asynchronous Operations to Task

With the new task library, setting up and calling asynchronous operations is far easier than the previous two approaches. First, I can use a single method signature and simplify specify the need for asynchronous operations by wrapping the result in a Task:

public interface IMultiplier
{
    Task<int> Multiply(int a, int b); 
}

For the implementation, I can easily use the built-in methods available in the library to spin off my thread:

public class Multiplier : IMultiplier
{
    public Task<int> Multiply(int a, int b)
    {
        //return Task.Factory.StartNew(() => a * b);
        return Task.Run(() => a * b); 

    }
}

Finally, I can use the new keywords to make calling and waiting for the result easy. When I want to do something asynchronously without blocking the thread I’m on, I simply modify the method with the async keyword, then await the asynchronous operaiton. Again, it’s as simple as async to mark the method’s intention of spinning of a separate task to wait for, then await to launch the thread and receive the results in a single line of code.

public async void DoTask()
{
    Console.WriteLine("Firing as task 4 * 5 ...");
    IMultiplier taskBased = new Multiplier();
    Console.WriteLine("Task result: {0}", await taskBased.Multiply(4, 5));
}       

What happens here is that the current thread runs up until the await operation. There, the operation is spun off on a new thread. The main thread will wait for that thread to complete but will not block – it is not a synchronous operation. When the concurrent thread finishes what it is doing, it will drop the result back on the calling thread and allow me to interrogate the result. Notice that I can even nest the call inside of other operations – here the task must actually complete before it can pass the result to the string formatter which in turn sends the output to the console.

Simple interface design, simple implementation, and simple execution. I like it! But what do I do about those existing events and APM-based interfaces?

Wrapping Events

Fortunately, it’s possible to bundle up any asynchronous operation into a task. For this reason, I almost always declare my interfaces using Task. That way I can hide the underlying implementation. Let’s test this out. How can I take my IMultiplier interface and use it to call my MultiplierEvent class? The trick is to use a TaskCompletionSource. This special class allows me to perform an asynchronous operation using any pattern I prefer and then set a result when I’m done. The token will expose the event as a task that can be awaited. Here is a wrapper class that implements the simple interface:

public class MultiplierEventAsTask : IMultiplier
{
    private IMultiplierEvent _event;

    public MultiplierEventAsTask()
    {
        _event = new MultiplierEvent();
    }

    public Task<int> Multiply(int a, int b)
    {
        var tcs = new TaskCompletionSource<int>();
        _event.MultiplyCompleted += (sender, args) =>
                {
                    tcs.SetResult(args.Result);
                };
        _event.MultiplyAsync(a, b); 
        return tcs.Task;
    }
}

I can then call it the same way I did the task-based implementation.

Wrapping the APM

Wrapping the APM model is even easier because the library provides a set of functions to convert existing operations. The FromAsync method will take most APM-style calls and turn them into tasks:

public class MultiplierApmAsTask : IMultiplier
{
    private IMultiplierApm _apm;

    public MultiplierApmAsTask()
    {
        _apm = new MultiplierApm();
    }

    public Task<int> Multiply(int a, int b)
    {
        return Task<int>.Factory.FromAsync(_apm.BeginMultiply, 
            _apm.EndMultiply, a, b, null);
    }
} 

Once again, the end result is the same simple interface despite a completely different implementation.

That’s a Wrap!

Using the Task we can now take various implementations and simplify them to a common, easy to use and understand interface. This little piece of code will execute each of the different implementations in order, waiting for the result but without blocking the main thread:

public async void DoAll()
{
    // convert event to a task 
    Console.WriteLine("Firing all converted events in order ...");
            
    IMultiplier taskFromEvent = new MultiplierEventAsTask();
    IMultiplier taskFromApm = new MultiplierApmAsTask();
    IMultiplier task = new Multiplier();

    Console.WriteLine("2 * 3 = {0}", await taskFromEvent.Multiply(2, 3));
    Console.WriteLine("4 * 5 = {0}", await taskFromApm.Multiply(4, 5));
    Console.WriteLine("6 * 7 = {0}", await task.Multiply(6, 7));            
}

There is a lot more you can do than simply await tasks. You can combine tasks, chain tasks, even wait for one or all tasks to complete before moving onto another task. Once you understand that async simply specifies the intention to do something asynchronously without blocking the main thread, and await simply launches a task and returns the result once that task is complete, you should be well on your way to simplifying your asynchronous development.

Download the sample project here.

Sunday, April 15, 2012

Sample Applications from Designing Silverlight Business Applications

I've received a few emails regarding the book that the code files are not available from the publisher website. I've spoken with the publisher about this and they are working to correct it, but I wanted to provide a link for those of you who have been patiently waiting. As a backup to the main website, I've posted all of the sample applications online to SkyDrive and you can download them by clicking on this link. I appreciate you patience and hope you will take the time to post a review on the site you purchased the book from once you have read and worked through the examples to help others who are considering picking it up for themselves.

Jeremy Likness

Monday, April 9, 2012

CodeStock 2012

Thanks for everyone's support and votes. I have been selected to present two sessions at CodeStock 2012.

Per the CodeStock website:

CodeStock is a two day event for technology and information exchange. Created by the community, for the community — this is not an industry trade show pushing the latest in marketing as technology, but a gathering of working professionals sharing knowledge and experience.

This is always a great conference. I have the added bonus of getting close to the corporate headquarters for Wintellect and visiting company co-founder Jeff Prosise. This year there were quite a few Wintellect employees selected to speak. I'll be there with Mitch Harpur (Come Get a Message at the SPA), Rik Robinson (CSS3: How to Fake It While They Bake It and Touring the jQuery UI Widget Factory), John Garland (Putting the Cloud in Your Pocket: A Guide to Using Windows Azure to Build Cloud-Enabled Windows Phone Apps), and our Technical Director Steve Porter.

I'll be doing two sessions:

MVVM for Modern Application Development

The Model-View-ViewModel pattern was introduced for Windows Presentation Foundation applications (WPF) and later exploded in popularity with the introduction of various frameworks to support development on additional platforms including Silverlight and Windows Phone. The release of KnockoutJS the pattern has extended MVVM to the web and exposed it to the JavaScript stack, while the new Windows 8 Metro platform embraces the same XAML and C#-based technologies that WPF and Silverlight pioneered. In this talk, Jeremy Likness takes a deep dive into the history of the pattern, describes its benefits, and discusses how it relates to modern application development. Is it a bad fit for web applications? Does it belong in the Metro space? Learn the benefits and trade-offs to help decide if this pattern makes sense in your projects moving forward.

Top 10 Developer Features in Windows 8 Metro

Windows 8 presents a new platform for application development called Metro. This platform is specifically focused on the tablet and slate market and provides many advanced features including touch-friendly interfaces and advanced power management features. Metro also introduces a new runtime known as WinRT that exposes some incredible contracts and interfaces that make it easier than ever before to build connected, collaborative, touch-friendly applications. Jeremy Likness shares the top 10 features developers will love about this platform. This is based on my recent article here with live code samples and demos.

It should be a very good conference and I hope you are able to make it. I'm always happy to connect with blog readers and Twitter followers so please don't hesitate to pop over and say "Hello" even if you can't make my sessions. It's tough putting together a schedule for this event because there are so many good talks. If you think you may be going, why not drop a line in the comments or ping me on Twitter? I look forward to seeing some of you there.

Jeremy Likness

Thursday, April 5, 2012

Designing Silverlight Business Applications Officially Released

 

slbookcover

In June of 2011 I started the journey of writing a Silverlight book. The Silverlight team was about to release version 5 with an incredible set of new features that would revolutionize how it can be used in the enterprise. I knew there were already a number of books available to use a reference for fundamentals and controls, so I wanted to dig deeper and hit the topics I was challenged with in my job as a consultant as well as those questions that continually seem to surface on blogs and forums. I began with an introduction that analyzed client technologies available at the time, especially focusing on how HTML5 was evolving but not yet mature. The focus of the book is my “sweet spot” as I have been developing Silverlight applications for the enterprise since it’s version 3 release in 2008.

No one could have realized just how much change would take place over the following year. Silverlight 5 was released but without a roadmap for version 6 and Windows 8 was announced. Fortunately it was soon discovered that Windows 8 provides a path to build applications using C# and XAML, has full support for running Silverlight 5, and through the Portable Class Library even provides a path to create code that can be used to target both present state and future state applications.

I had the privilege of working with a phenomenal team at Addison-Wesley Professional along with two very experienced Silverlight developers as technical editors who helped shape the book to contain the depth and quality of information that is available today.

The book is in stock at Amazon.com as of today. There are a number of ways you can order the book:

The publisher’s website provides you with the table of contents and provides a sample chapter to download that covers the Model-View-View Model (MVVM) pattern.

The book also features the Jounce MVVM Open Source Framework I developed along with a sample application that covers quite a few features.

Is this book relevant? I believe it is if you’ll accept my biased opinion because companies have Line of Business applications today, they are not releasing Windows 8 applications right now, and Silverlight remains a very viable solution for these applications. The majority of concepts covered in this book translate to the C#/XAML stack used for Windows 8 Metro applications and apply to building enterprise applications in general. There has been tremendous support for this and I’ve included some of the most difficult patterns and problems to tackle with solutions that translate to other platforms as well.

I want to thank the community for their incredible support as it has been an amazing journey. I also would ask that if you have invested in the Rough Cuts, eBooks, paperback, or other editions, that once you’ve had time to read this book you take the time to post your review and comments online. It is your reviews and comments that other developers will trust when they are making the decision to invest, so honest feedback helps them decide whether or not this is a resource that will provide them with value. It also helps me improve how I deliver content to make it the best possible quality for you.

So what’s next for me? I’m already several chapters into my next book. It will cover Building Windows 8 Metro Applications with C# and XAML, and I’ll include information about how Silverlight developers today can take advantage of the Metro platform for tomorrow’s applications. This book will be available for early access to read, review, and provide feedback through the Safari Rough Cuts program. Stay tuned and I’ll announce when more information becomes available.

Thanks again!