Wintellect Blogs

Taming Asynchronous Tasks in JavaScript with Zone.js

Jeremy Likness

7 Feb , 2014  

I recently learned about a new project by the Angular team called Zone. This project is one of those rare gems that is only a few lines of code but is so groundbreaking it literally takes time to wrap your mind around it. The easiest way to get started with Zone is to watch the excellent talk by its creator, Brian Ford. He demos some pretty cool scenarios that are all in the project repository.

In a nutshell, Zone provides what you might consider a “thread execution” context for JavaScript. It basically takes the current “context” you are in and intercepts all asynchronous events so they “map” to the same context. This enables you to do some pretty interesting things such as view stack traces through the original wire-up (i.e. you no longer get “disconnected” at the point the event was raised) or add tooling. You can use Zone to change the behavior of events (such as implementing your own version of setTimeout) and to keep track of tasks.

Zone works by simply running something in the context of the Zone. You can have multiple Zones with their own context. To steal an example from the Zone repo, consider this:

zone.
Read more

, ,

Wintellect Blogs

Coroutines for Asynchronous Sequential Workflows using Reactive Extensions (Rx)

Jeremy Likness

15 Apr , 2013  

I’ve been doing quite a bit with Reactive Extensions (Rx) for Silverlight lately. One idea that I keep exploring is the concept of creative intuitive sequential workflows for asynchronous operations. You can read about my explorations using Wintellect’s own Power Threading Library in this post along with a simple solution using an interface and enumerators in part 2 of that series. I’m tackling the problem from a different angle.

First, my disclaimers: this is more of an exploratory, “Here’s what can be done” post. Please don’t take this as best practice or guidance, but more of another way of looking at the solution as well as an opportunity to dive deeper into Reactive Extensions. Also understand I am by no means an expert with Rx so I welcome feedback related to this experiment.

The concept is straightforward: there are often times we want an asynchronous set of operations to perform sequentially. Perhaps you must load a list from a service, then load the selected item, then trigger an animation. This can be done either by chaining the completed events or nesting lambda expressions, but is there a cleaner way?

To me, a cleaner solution would make it easy to see what happens sequentially, and also easy to fire the sequence.… Read more

, ,

Wintellect Blogs

Asynchronous Commands in Windows Store Apps

Jeremy Likness

11 Mar , 2013  

The Model-View-View Model (MVVM) pattern is more popular than ever and is built into the Visual Studio templates for creating Windows Store apps. Developers familiar with Silverlight already encountered the platform shift to using asynchronous operations because it was impossible to generate a WCF client with synchronous methods. The Windows Runtime (WinRT) takes this further by dictating any operation that may potentially take longer than 50ms to complete should be asynchronous.

How does the MVVM pattern handle asynchronous operations, when the command interface ICommand only exposes synchronous methods?

namespace System.Windows.Input
{
     public interface ICommand
     {
         event EventHandler CanExecuteChanged;
         bool CanExecute(object parameter);
         void Execute(object parameter);
     } }

Now consider a simple implementation of a command we’ll call an ActionCommand because it allows you to specify a delegate to perform and action when it is invoked. It also provides a predicate to condition the command and a public method to notify the command when the conditions for the predicate have changed.

namespace MyApp.Common
{
     using System;
     using System.Windows.Input;
     public class ActionCommand : ICommand
      {
         private readonly Action action;
         private readonly Func<bool> condition;

         public ActionCommand()
         {
             this.action = delegate { };
             this.condition = () => true;
         }
         public ActionCommand(Action action)
         {
             this.action = action;
             this.condition = () => true;
         }




         public ActionCommand(Action action, Func<bool> condition)
         {
             this.action = action;
             this.condition = condition;
         }
        

public event EventHandler CanExecuteChanged = delegate { };
         public void RaiseExecuteChanged()
         {
             this.CanExecuteChanged(this, EventArgs.Empty);
         }
         public bool CanExecute(object parameter)
         {
             return this.condition();
         }
         public void Execute(object parameter)
     ;     {
             this.action();
         }
     } }

As you can see, there is no Task in the implementation of ICommand, nor any asynchronous code.… Read more

,

Wintellect Blogs

The Task: Async and Await in a Windows Runtime World

Jeremy Likness

14 May , 2012  

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.… Read more

,

Wintellect Blogs

Silverlight 5 RC – Using the Task Parallel Library (TPL)

Jeremy Likness

1 Sep , 2011  

One enhancement that quietly slipped into the Silverlight 5 RC is the inclusion of Tasks. This is not the full-blown Task Parallel Library (TPL) to my knowledge (as it lacks the Parallel class and extensions) but it does provide Task, its related factories, and the functionality to chain and monitor tasks. The purpose of the library is to simplify asynchronous methods.

This post will show you an example of using the library. I’m not presenting this as a best practice, but only as a thought exercise to show you the use of the Task library in a visual way. The program computes the factorials of several numbers, but uses task continuation to ensure only one web service call is made at a time (thus simulating a sequential asynchronous workflow). You can modify the example to fire all threads simultaneously.

First, a simple service in the web project to compute the factorial:

[ServiceContract(Namespace = "http://jeremylikness.com/examples/")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SimpleService
{
    [OperationContract]
    public long Factorial(int value)
    {
        long result = value;
        while (--value 0)
        {
            result *= value;
        }
        return result;
    }       
}

Add the service reference to the Silverlight project. Next, create a simple class in the Silverlight project to hold the value and the result that implements property change notifications:

public class Factorial : INotifyPropertyChanged 
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            RaisePropertyChange("Value");
        }
    }

    private long _result;
    public long Result
    {
        get { return _result; }
        set
        {
            _result = value;
            RaisePropertyChange("Result");
        }
    }

    protected void RaisePropertyChange(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

The main page holds a button to fire off the calls and a list box to show the results:

<Grid x:Name="LayoutRoot" Background="White"<Grid.RowDefinitions<RowDefinition Height="Auto"/<RowDefinition Height="Auto"/</Grid.RowDefinitions<ListBox Grid.Row="1" x:Name="FactorialList"<ListBox.ItemTemplate<DataTemplate<StackPanel Orientation="Horizontal"<TextBlock Text="{Binding Value}"/<TextBlock Text="!="/<TextBlock Text="{Binding Result}"/</StackPanel</DataTemplate</ListBox.ItemTemplate</ListBox<Button Click="_BtnFactorClick" x:Name="btnFactor" IsEnabled="False" 
            Content="Factor" HorizontalAlignment="Left"
            VerticalAlignment="Top" Margin="10"/</Grid

In the code-behind for the main page, hold a list of the Factorial objects:

private readonly List<Factorial_factorials;

Then populate it with the numbers 1 through 20 and bind it to the list box – at this point you can run the application and see the list of numbers to be factored:

public MainPage()
{
    InitializeComponent();

    _factorials = new List<Factorial();
            
    for (var x = 0; x < 20; x++)
    {
        _factorials.Add(new Factorial {Value = x + 1});
    }

    FactorialList.ItemsSource = _factorials;
}

Add the code to create a channel for the service.… Read more

, ,

Wintellect Blogs

Using the Task Parallel Library (TPL) for Events

Jeremy Likness

27 Jun , 2011  

The parallel tasks library was introduced with the .NET Framework 4.0 and is designed to simplify parallelism and concurrency. The API is very straightforward and usually involves passing in an Action to execute. Things get a little more interesting when you are dealing with asynchronous models such as events.

While the TPL has explicit wrappers for the asynchronous programming model (APM) that you can read about here: TPL APM Wrappers, there is no explicit way to manage events.

I usually hide the “muck” of subscribing and waiting for a completed action in events with a callback. For example, the following method generates a random number. I’m using a delay to simulate a service call and a thread task to make the call back asynchronous: you call into the method, then provide a delegate that is called once the information is available.

private static void _GenerateRandomNumber(Action<intcallback)
{
    var random = _random.Next(0, 2000) + 10;
    Console.WriteLine("Generated {0}", random);
    Task.Factory.StartNew(() ={
                                    Thread.Sleep(1000);
                                    callback(random);
                                }, TaskCreationOptions.None);
}

Now consider an algorithm that requires three separate calls to complete to provide the input values in order to compute a result. The calls are independent so they can be done in parallel. The TPL supports “parent” tasks that wait for their children to complete, and a first pass might look like this:

private static void _Incorrect()
{
            
    var start = DateTime.Now;

    int x = 0, y = 0, z = 0;

    Task.Factory.StartNew(
        () ={
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =x = result),
                                        TaskCreationOptions.AttachedToParent);
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =y = result),
                                        TaskCreationOptions.AttachedToParent);
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =z = result),
                                        TaskCreationOptions.AttachedToParent);
            }).ContinueWith(t ={
                                    var finish = DateTime.Now;
                                    Console.WriteLine("Bad Parallel: {0}+{1}+{2}={3} [{4}]",
                                        x, y, z,
                                        x+y+z,
                                        finish - start);
                                    _Parallel();                                            
                                });          
}

The code aggregates several tasks to the parent, the parent then waits for the children to finish and continues by computing the time span and showing the result.… Read more

,

Wintellect Blogs

Using the Task Parallel Library (TPL) for Events

Jeremy Likness

27 Jun , 2011  

The parallel tasks library was introduced with the .NET Framework 4.0 and is designed to simplify parallelism and concurrency. The API is very straightforward and usually involves passing in an Action to execute. Things get a little more interesting when you are dealing with asynchronous models such as events.

While the TPL has explicit wrappers for the asynchronous programming model (APM) that you can read about here: TPL APM Wrappers, there is no explicit way to manage events.

I usually hide the “muck” of subscribing and waiting for a completed action in events with a callback. For example, the following method generates a random number. I’m using a delay to simulate a service call and a thread task to make the call back asynchronous: you call into the method, then provide a delegate that is called once the information is available.

private static void _GenerateRandomNumber(Action<intcallback)
{
    var random = _random.Next(0, 2000) + 10;
    Console.WriteLine("Generated {0}", random);
    Task.Factory.StartNew(() ={
                                    Thread.Sleep(1000);
                                    callback(random);
                                }, TaskCreationOptions.None);
}

Now consider an algorithm that requires three separate calls to complete to provide the input values in order to compute a result. The calls are independent so they can be done in parallel. The TPL supports “parent” tasks that wait for their children to complete, and a first pass might look like this:

private static void _Incorrect()
{
            
    var start = DateTime.Now;

    int x = 0, y = 0, z = 0;

    Task.Factory.StartNew(
        () ={
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =x = result),
                                        TaskCreationOptions.AttachedToParent);
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =y = result),
                                        TaskCreationOptions.AttachedToParent);
                Task.Factory.StartNew(() =_GenerateRandomNumber(result =z = result),
                                        TaskCreationOptions.AttachedToParent);
            }).ContinueWith(t ={
                                    var finish = DateTime.Now;
                                    Console.WriteLine("Bad Parallel: {0}+{1}+{2}={3} [{4}]",
                                        x, y, z,
                                        x+y+z,
                                        finish - start);
                                    _Parallel();                                            
                                });          
}

The code aggregates several tasks to the parent, the parent then waits for the children to finish and continues by computing the time span and showing the result.… Read more

,

Wintellect Blogs

Silverlight and WCF Service Consumption: Event vs. APM

Jeremy Likness

29 Nov , 2010  

I’ve blogged several times about how I like to handle services in Silverlight. For two key posts, take a look at:

In this post we’ll explore the difference between using the actual contract for a WCF service in Silverlight versus using the generated client. The difference is subtle but important, and involves not only the event-based model and the Asynchronous Programming Model (APM) but also some nuances with threads.

There is no code project for this because the nuance is in the way you call the service, not the example itself, but there should be enough code in this post for you to recreate the example if you want to test it yourself.

Here’s the rub: let’s create a simple service that adds two integers and returns the result. The contract is simply:

[ServiceContract(Namespace = "http://jeremylikness.com/silverlight/")]
public interface IAddService
{
    [OperationContract]
    int Add(int x, int y);
}

Now we can implement it – just add the numbers and return the value:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AddService : IAddService
{        
    public int Add(int x, int y)
    {
        return x + y;
    }        
}

So that’s easy enough (and we’ve jumped through our first Silverlight hoop by flagging the service with the compatibility attribute).… Read more

, ,

Wintellect Blogs

Sequential Asynchronous Workflows Part 2: Simplified

Jeremy Likness

25 Mar , 2010  

I received quite a bit of feedback related to my sequential asynchronous workflows post. Most people asked if I could simplify the example even more and/or show the inner workings of the coroutine engine itself. Because the source for the library I demonstrated in the last post is not available, I’ve put together a very simple solution to help you better understand and take advantage of coroutines.

First, the fine print. This framework is simply to help understand the concept and provide a starting point for building out coroutines yourself. I know some companies simple don’t allow third-party code and it always helps to learn a framework by starting at the ground floor. Some things you won’t find here that would belong in production code include thread-awareness (background or UI thread?), timeouts (i.e. if I call out and it never returns, does my workflow die?) and exception management. All very important but reasons why this framework is educational and not a “production-ready” implementation.

Download the source for this post

Remember the original interface we defined for illustration purposes, the ICoroutine interface? Here it is:

public interface ICoroutine
{
    void Yield();
    Action Yielded { get; set; }
}

Now, to drive a workflow, you simply need an engine.… Read more

Wintellect Blogs

Simple Dialog Service in Silverlight

Jeremy Likness

23 Jan , 2010  

I noticed on the forums there are a lot of users not comfortable with asynchronous programming who struggle a bit in Silverlight with getting their arms around the concept of a dialog box. In other environments, you can simply shoot out a dialog, wait for the response, and continue. In Silverlight, of course, the action is asynchronous. I would argue it should be this way most of the time.

The problem is that many people tend to take the approach of trying to force the process into a synchronous one, instead of changing the way they think and approach the application. There is a reason why processes are asynchronous in Silverlight. There is one main UI thread, and a blocking process would block the entire thread and effectively freeze the Silverlight application. Having the process asynchronous allows you to continue to render graphics elements, perform actions in the background, even display a soothing animation while you await the user’s response.

I spoke to a more highly decoupled approach in a post awhile ago that was more an experiment with the event aggregator: Decoupled Child Window Dialogs with Silverlight and PRISM. Here, I want to show the more straightforward approach.

The first step is to choose what the dialog will be displayed with.… Read more

,