Showing posts with label AsyncCTP. Show all posts
Showing posts with label AsyncCTP. Show all posts

Sunday, September 4, 2011

Programming with C# asynchronous sequences

Tomas Petricek in his last blog post titled “Programming with F# asynchronous sequences” presents F# implementation of something called asynchronous sequences. In this post I will show you how the same concept can be implemented in C#. Let’s look at the sample code below to better understand what the asynchronous sequence is:

IEnumerable<...> AsyncSeq()
{
yield return "Hello";
await TaskEx.Delay(100);
yield return "world!";
}

Asynchronous sequences is a code that produces the sequence of values generated on demand (this is how the IEnumerable interface can be interpreted) but additionally does some asynchronous work during the evaluation process (await keyword). Every time the client of asynchronous sequence calls MoveNext method, next value is being evaluated. The key feature here is that the client decides when to produce next value and when to stop the processing.

There are two problems with such an implementation of asynchronous sequence. Sequences in .Net world are represented with IEnumerable interface, but the interface allows only synchronous processing. Since the MoveNext method returns bool value in the interface implementation, we need to immediately decide whether the next value can be produced or not. In the asynchronous processing it can take a few minutes or even hours to provide such information. The second problem is that so far we cannot mix together await keyword (Async Ctp) with yield return/yield break keywords inside the same method body. My solution resolves those two problems and the above sequence can be implemented the fallowing way:

IEnumerable<AsyncSeqItem<string>> AsyncSeq()
{
yield return "Hello";
yield return TaskEx.Delay(100);
yield return "world!";
}

public enum AsyncSeqItemMode
{
Value, Task, Sequence
}

public class AsyncSeqItem<T>
{
public AsyncSeqItemMode Mode { get; private set; }
public T Value { get; private set; }
public Task Task { get; private set; }
public IEnumerable<AsyncSeqItem<T>> Seq { get; private set; }

public AsyncSeqItem(T value)
{
Value = value;
Mode = AsyncSeqItemMode.Value;
}

public AsyncSeqItem(Task task)
{
Task = task;
Mode = AsyncSeqItemMode.Task;
}

public AsyncSeqItem(IEnumerable<AsyncSeqItem<T>> seq)
{
Seq = seq;
Mode = AsyncSeqItemMode.Sequence;
}

public static implicit operator AsyncSeqItem<T>(T value)
{
return new AsyncSeqItem<T>(value);
}

public static implicit operator AsyncSeqItem<T>(Task task)
{
return new AsyncSeqItem<T>(task);
}
}

AsyncSeqItem represents one of three following values:

  • Value – next value generated by the sequence
  • Task – some asynchronous work that needs to be awaited for before going forward
  • Sequence – it’s used with recursive calls and it means that we want to use tail recursion

There are two ways of consuming such sequence in the client:

public static class AsyncSeqExtensions
{
public static IEnumerable<Task<Option<T>>> ToTaskEnumerable<T>(this IEnumerable<AsyncSeqItem<T>> seq, bool continueOnCapturedContext = true)
{ ... }

public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<AsyncSeqItem<T>> seq, bool continueOnCapturedContext = true)
{ ... }
}

public class Option<T>
{
public T Value { get; private set; }
public bool HasValue { get; private set; }

public Option()
{
HasValue = false;
}

public Option(T value)
{
Value = value;
HasValue = true;
}

public static implicit operator Option<T>(T value)
{
return new Option<T>(value);
}
}

In the first approach we are calling ToAsyncEnumerable extension method returning the sequence of tasks. Each task wraps special type called Option<T> which can be used similarly to Nullable<T> type except that it works with value and reference types. Returning task with option object without the value means that we reached the end of the sequence. I also provide few standard LINQ operators built on the top of such a sequence semantic:

public static class AsyncSeqExtensions
{
async private static Task ForEachTaskImpl<T>(this IEnumerable<Task<Option<T>>> seq, Action<Task<Option<T>>> action)
{
foreach (var task in seq)
{
await task;
action(task);
}
}
public static Task ForEachTask<T>(this IEnumerable<Task<Option<T>>> seq, Action<Task<Option<T>>> action)
{
return ForEachTaskImpl(seq, action);
}

public static Task ForEach<T>(this IEnumerable<Task<Option<T>>> seq, Action<T> action)
{
return seq.ForEachTask(task =>
{
if(task.Result.HasValue)
action(task.Result.Value);
});
}

async private static Task<T[]> ToArrayImpl<T>(IEnumerable<Task<Option<T>>> seq)
{
var list = new List<T>();
await seq.ForEach(v => list.Add(v));
return list.ToArray();
}
public static Task<T[]> ToArray<T>(this IEnumerable<Task<Option<T>>> seq)
{
return ToArrayImpl(seq);
}

public static IEnumerable<Task<Option<TResult>>> Select<T, TResult>(this IEnumerable<Task<Option<T>>> source,
Func<T,TResult> selector) { ... }

public static IEnumerable<Task<Option<T>>> Where<T>(this IEnumerable<Task<Option<T>>> source,
Func<T, bool> predicate) { ... }

public static IEnumerable<Task<Option<T>>> Take<T>(this IEnumerable<Task<Option<T>>> source,
int count) { ... }

...
}

Returning additional task object at the end of a sequence with special value allows us to use standard IEnumerable<T> interface but it’s a little bit inconvenient. In the second approach we use the IAsyncEnumerable interface from the Reactive Framework library released some time ago.

public interface IAsyncEnumerable<out T>
{
IAsyncEnumerator<T> GetEnumerator();
}

public interface IAsyncEnumerator<out T> : IDisposable
{
Task<bool> MoveNext();
T Current { get; }
}

public static class AsyncEnumerable
{
public static IAsyncEnumerable<TResult> Select<TSource, TResult>(IAsyncEnumerable<TSource> source,
Func<TSource, TResult> selector) { ... }

public static IAsyncEnumerable<TSource> Where<TSource>(IAsyncEnumerable<TSource> source,
Func<TSource, bool> predicate) { ... }

public static IAsyncEnumerable<TSource> Take<TSource>(IAsyncEnumerable<TSource> source,
int n) { ... }
}

This interface perfectly represents the semantic of asynchronous sequence. Rx library also provides many standard LINQ operations like: Where, Select, Take, Sum, First and so on. This allows us to write almost any LINQ query executing on the top of asynchronous sequence.

Now let’s summarize what we achieved so far. We can write imperative code implementing asynchronous sequence. We can use extension method to create one of two asynchronous sequence representations. Finally we can iterate through all items in such a sequence or we can build a new sequence object using LINQ operators.

The C# version of the web crawler presented in Tomas Petricek’s blog post could look like this:

public static class AsyncSeqSample
{
async public static Task CrawlBingUsingAsyncEnumerable()
{
await RandomCrawl("http://news.bing.com")
.ToAsyncEnumerable()
.Where(t => !t.Item1.Contains("bing.com"))
.Select(t => t.Item2)
.Take(10)
.ForEach(Console.WriteLine);

Console.WriteLine("the end...");
}

async public static Task CrawlBingUsingTaskEnumerable()
{
await RandomCrawl("http://news.bing.com")
.ToTaskEnumerable()
.Where(t => !t.Item1.Contains("bing.com"))
.Select(t => t.Item2)
.Take(10)
.ForEach(Console.WriteLine);

Console.WriteLine("the end...");
}

public static IEnumerable<AsyncSeqItem<Tuple<string, string>>> RandomCrawl(string url)
{
return RandomCrawlLoop(url, new HashSet<string>());
}

private static IEnumerable<AsyncSeqItem<Tuple<string,string>>> RandomCrawlLoop(string url, HashSet<string> visited)
{
if (visited.Add(url))
{
var downloadTask = DownloadDocument(url);
yield return downloadTask;
if (downloadTask.Result.HasValue)
{
var doc = downloadTask.Result.Value;
yield return Tuple.Create(url, GetTitle(doc));
foreach (var link in ExtractLinks(doc))
{
foreach (var l in RandomCrawlLoop(link, visited))
{
yield return l;
}
}
}
}
}

private static string[] ExtractLinks(HtmlDocument doc)
{
try
{
var q = from a in doc.DocumentNode.SelectNodes("//a")
where a.Attributes.Contains("href")
let href = a.Attributes["href"].Value
where href.StartsWith("http://")
let endl = href.IndexOf('?')
select endl > 0 ? href.Substring(0, endl) : href;

return q.ToArray();
}
catch
{
return new string[0];
}
}

async private static Task<Option<HtmlDocument>> DownloadDocument(string url)
{
try
{
var client = new WebClient();
var html = await client.DownloadStringTaskAsync(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
return new Option<HtmlDocument>(doc);
}
catch (Exception)
{
return new Option<HtmlDocument>();
}
}

private static string GetTitle(HtmlDocument doc)
{
var title = doc.DocumentNode.SelectSingleNode("//title");
return title != null ? title.InnerText.Trim() : "Untitled";
}
}

Now let’s see how ToAsyncEnumerable and ToTaskEnumerable methods have been implemented:

public static class AsyncSeqExtensions
{
public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<AsyncSeqItem<T>> seq, bool continueOnCapturedContext = true)
{
if (seq == null) throw new ArgumentNullException("seq");

return new AnonymousAsyncEnumerable<T>(() =>
{
var enumerator = seq.ToTaskEnumerable(continueOnCapturedContext).GetEnumerator();
seq = null; // holding reference to seq parameter introduces memory leaks when asynchronous sequence uses recursive calls
TaskCompletionSource<bool> currentTcs = null;
Task<Option<T>> currentTask = null;

return new AnonymousAsyncEnumerator<T>(
() =>
{
currentTcs = new TaskCompletionSource<bool>();

if (CheckEndOfSeq(currentTask) == false)
{
currentTcs.SetResult(false);
return currentTcs.Task;
}

enumerator.MoveNext();

enumerator.Current.ContinueWith(t =>
{
if (t.IsFaulted)
{
currentTcs.SetException(t.Exception);
}
else
{
if (!t.Result.HasValue)
{
currentTcs.SetResult(false);
}
else
{
currentTask = t;
currentTcs.SetResult(true);
}
}
});

return currentTcs.Task;
},
() => currentTask.Result.Value
);
});
}

public static IEnumerable<Task<Option<T>>> ToTaskEnumerable<T>(this IEnumerable<AsyncSeqItem<T>> seq, bool continueOnCapturedContext = true)
{
if (seq == null) throw new ArgumentNullException("seq");

return new AnonymousEnumerable<Task<Option<T>>>(() =>
{
var synchronizationContext = continueOnCapturedContext ? SynchronizationContext.Current : null;

var enumerator = seq.GetEnumerator();
seq = null; // holding reference to seq parameter introduces memory leaks when asynchronous sequence uses recursive calls

TaskCompletionSource<Option<T>> currentTcs = null;

return new AnonymousEnumerator<Task<Option<T>>>(
() =>
{
if (CheckEndOfSeq(currentTcs) == false)
return false;

currentTcs = new TaskCompletionSource<Option<T>>();

Action moveNext = null;
moveNext = () =>
{
Start:

bool b;

try
{
b = enumerator.MoveNext();
}
catch (Exception exception)
{
currentTcs.SetException(exception);
return;
}

if (b == false)
{
currentTcs.SetResult(new Option<T>());
}
else
{
var c = enumerator.Current;
if (c.Mode == AsyncSeqItemMode.Value)
{
currentTcs.SetResult(c.Value);
}
else if (c.Mode == AsyncSeqItemMode.Task)
{
if (synchronizationContext != null)
c.Task.ContinueWith(_ => synchronizationContext.Post(s => ((Action)s)(), moveNext));
else
c.Task.ContinueWith(_ => moveNext());
}
else if (c.Mode == AsyncSeqItemMode.Sequence)
{
enumerator = c.Seq.GetEnumerator();
goto Start;
}
}
};

moveNext();

return true;
},
() => currentTcs.Task
);
});
}
}

As you can see the implementation is really simple but the whole concept of asynchronous sequence is very powerful.

Download

Thursday, May 5, 2011

Simplifying XNA game development using Async CTP or F# asynchronous workflow (GameAwaiter)

Last time I have been writing about launching the Async CTP on WP7 platform. The Async CTP Refresh has been released during MIX 2011 and finally WP7 platform is supported, so my last post is quite obsolete right now. But I hope that, after reading it, you better understand how Async CTP works underneath.

This time we will go one step forward. Once we have Tasks on WP7 and two new keywords await and async in C# we can use all that to change the way we write games in XNA.

If you know something about TPL and XNA framework it may seem a bit strange how I am going to mix them both since at first look TPL is all about building multithreaded applications and XNA application uses one single thread in most cases.

I will not not write too much about XNA framework itself  (especially because I am a beginner in game development :) ) but if you try writing even a very simple 2D game you will find out that code for XNA is really hard to understand and maintain. Probably you will have many fields storing state of the game items, many boolean flags and a lot of if-then-else statements changing that state. You can say that the game is actually one big state machine. That’s what I’ve found out after writing my fist game in XNA.

Async CTP can change the structure of the code dramatically so we can easily discover the flow of the game logic and what is most interesting everything is running on single thread.

In this post I will show you three implementations of a very simple 2D game called Smiley. All of those implementations use XNA framework but the first one is a typical XNA approach and the last two are totally different. They are using Async CTP and the F# asynchronous workflow.

image

I took the idea for the game from the Tomas Petricek’s master thesis and it can be presented on the three screens:

image

image

 image

We tap the screen to start the game, then we have 20 seconds to hit moving Smiley image as many times as we can and at the end the number of hits is displayed for 4 seconds. The first screen appears again. The Smiley position is changing in 2 seconds periods or directly after tapping on it.

Originally, that game was implemented in F# using Joinads. A few months ago I have implemented that game also in F# using Reactive Framework and treating the IObservable<T> type as the Monad type. With that I built my own workflow builder. I will try to describe that approach in the next blog post but now let’s come back to the subject of today’s post.

As you can see in the class diagram above, all three implementations have a common base class called SmileyGameBase. That class inherits from Game class which is the main XNA component representing the whole game. And all we need to do when writing an XNA game is to override two methods: Update and Draw. Update method is responsible for recalculating the game state and the Draw method draws all game items like texts, textures and so on. Both methods are called by XNA environment (Update before Draw) many times during each second when the game is running (about 30 times per second on WP7). In our game the Draw method looks the same in all three cases but the Update is specific for each of them.

public abstract class SmileyGameBase : Game
{
    // ... 

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        _spriteBatch.Begin();

        if (_isRunning)
        {
            float fontScale = 2;
            _spriteBatch.DrawString(_spriteFont, "time : " + _time, new Vector2(10, 5), 
                Color.White, 0, Vector2.Zero, fontScale, SpriteEffects.None, 0);
            _spriteBatch.DrawString(_spriteFont, "score : " + _score, new Vector2(500, 5), 
                Color.White, 0, Vector2.Zero, fontScale, SpriteEffects.None, 0);

            _spriteBatch.Draw(_smileyTexture, _smileyPosition, Color.White);
        }
        else
        {
            float fontScale = 3;
            _spriteBatch.DrawString(_spriteFont, _message, new Vector2(10, 100), 
                Color.Red, 0, Vector2.Zero, fontScale, SpriteEffects.None, 0);
        }

        _spriteBatch.End();

        base.Draw(gameTime);
    }
}

The code is pretty simple, we have few fields representing the game state and the Draw method draws Smiley image and prints some text messages. Now let’s look at the XNA and Async CTP implementations to compare them together.

This is the Async CTP implementation.

using System.Threading.Tasks;
using Microsoft.Xna.Framework.Input.Touch;
    
namespace SmileyGame.Common
{
    using AsyncXnaIntegration;
   
    public abstract class AsyncCtpGame : SmileyGameBase
    {
        private GameAwaiter _gameAwaiter;

        protected AsyncCtpGame()
        {
            _gameAwaiter = new GameAwaiter(this);
            Components.Add(_gameAwaiter);
        }

        protected override void LoadContent()
        {
            base.LoadContent();
            StartMenu();
        }

        async private void StartMenu()
        {
            while (true)
            {
                _message = "tap to start the game ... ";
                await _gameAwaiter.Gesture(GestureType.Tap);
                _isRunning = true;
                await StartGame();
                _isRunning = false;
                _message = "your score : " + _score;
                await _gameAwaiter.Delay(4000);
            }
        }

        async private Task StartGame()
        {
            _score = 0;
            var timer = StartTimer(GameDuration);

            while (true)
            {
                var match = await _gameAwaiter.WhenAny(timer,
                    _gameAwaiter.Delay(ChangePositionPeriod), _gameAwaiter.Gesture(IsSmileyClicked));
                switch (match.Index)
                {
                    case 0:
                        return;

                    case 1:
                        _smileyPosition = GetRandomPostion();
                        break;

                    case 2:
                        _smileyPosition = GetRandomPostion();
                        _score++;
                        break;

                    default: break;
                }

            }
        }

        async private Task StartTimer(int n)
        {
            while (n >= 0)
            {
                _time = n;
                await _gameAwaiter.Delay(TimerPeriod);
                n--;
            }
        }
    }
}

And here is the pure XNA implementation.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;

namespace SmileyGame.Common
{
    public abstract class XnaGame : SmileyGameBase
    {
        protected XnaGame()
        {
            _message = "tap to start the game ... ";
        }

        private TimeSpan _nextTimerTime;
        private TimeSpan _nextChangePostionTime;
        private TimeSpan? _nextDisplayFinalScoreTime;
        
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            var gestures = GetGestures();

            if (!_isRunning)
            {
                if (_nextDisplayFinalScoreTime.HasValue)
                {
                    if (gameTime.TotalGameTime > _nextDisplayFinalScoreTime.Value)
                    {
                        _nextDisplayFinalScoreTime = null;
                        _message = "tap to start the game ... ";
                    }   
                }
                else if (gestures.Any(g => IsGestureType(g, GestureType.Tap)))
                {
                    _isRunning = true;
                    _score = 0;
                    _time = GameDuration;
                    _nextTimerTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(TimerPeriod);
                    _nextChangePostionTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(ChangePositionPeriod);
                }
            }
            else
            {                
                if (gameTime.TotalGameTime > _nextTimerTime )
                {
                    _time--;
                    _nextTimerTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(TimerPeriod);
                    if (_time < 0)
                    {
                        _isRunning = false;
                        _nextDisplayFinalScoreTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(4000);
                        _message = "your score : " + _score;
                    }                    
                }
                else if (gameTime.TotalGameTime > _nextChangePostionTime )
                {
                    _smileyPosition = GetRandomPostion();
                    _nextChangePostionTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(ChangePositionPeriod);
             
                }
                else if (gestures.Any(IsSmileyClicked))
                {
                    _smileyPosition = GetRandomPostion();
                    _nextChangePostionTime = gameTime.TotalGameTime + TimeSpan.FromMilliseconds(ChangePositionPeriod);
                    _score++;
                }
            }
        }

        private static bool IsGestureType(GestureSample gestureSample, GestureType gestureType)
        {
            return (gestureSample.GestureType & gestureType) == gestureType;
        }

        private static List<GestureSample> GetGestures()
        {
            var gestures = new List<GestureSample>();
            while (TouchPanel.IsGestureAvailable)
                gestures.Add(TouchPanel.ReadGesture());
            return gestures;
        }
    }
}

When we read first implementation we can easily discover the flow of the program and the order of particular pieces of code look natural. In the pure XNA approach it is really hard to understand how the game works internally and how to extend them. Let’s image that we would like to display sequentially “3” “2” “1” “start” just after first tap in 1 second periods. Think how to do it in each of these two approaches ?

So now lets go to F# implementation. F# has something called asynchronous workflow which was available for F# developers long before Async CTP (and in fact it was the inspiration for Async CTP authors) the F# implementation is very similar to Async CTP one.

namespace SmileyGame.FSharp

open SmileyGame.Common
open AsyncXnaIntegration
open SmileyGame.FSharp.Extensions
open Microsoft.Xna.Framework.Input.Touch

type FSharpGame() as this =
  inherit SmileyGameBase()
  let _gameAwaiter = new GameAwaiter(this)
  do this.Components.Add(_gameAwaiter)

  // access to protected members
  member private this.set_smileyPosition p = this._smileyPosition <- p
  member private this.set_time t = this._time <- t 
  member private this.set_score s = this._score <- s
  member private this.set_message m = this._message <- m
  member private this.set_isRunning r = this._isRunning  <- r
  member private this.inc_score() = this._score <- this._score + 1  
  member private this.get_score = this._score
  member private this.get_TimerPeriod = SmileyGameBase.TimerPeriod
  member private this.get_GameDuration = SmileyGameBase.GameDuration  
  member private this.get_ChangePositionPeriod = SmileyGameBase.ChangePositionPeriod  
  member private this.IsSmileyClicked g = base.IsSmileyClicked g
  member private this.GetRandomPostion() = base.GetRandomPostion()
  
  member private this.StartTimer n =
    let n = ref n
    async {      
      while !n >= 0 do        
        this.set_time !n
        do! _gameAwaiter.Delay(this.get_TimerPeriod) |> Async.AwaitTask
        n := !n - 1
    }

  member private this.StartGame() =
    async {
    do this.set_score 0
    let timer = this.StartTimer(this.get_GameDuration) |> Async.ToTask
    let c = ref true
    while !c do
      let! m = _gameAwaiter.WhenAny(timer,_gameAwaiter.Delay(this.get_ChangePositionPeriod), _gameAwaiter.Gesture(this.IsSmileyClicked)) |> Async.AwaitTask
      match m.Index with
      | 0 -> c := false
      | 1 -> this.set_smileyPosition(this.GetRandomPostion())
      | 2 -> this.set_smileyPosition(this.GetRandomPostion()) ; this.inc_score()
      | _ -> ()
    }

  member private this.StartMenu() =
    async {
      while true do
        this.set_message "tap to start the game ... "
        let! _ = _gameAwaiter.Gesture(GestureType.Tap) |> Async.AwaitTask
        this.set_isRunning true
        do! this.StartGame()
        this.set_isRunning false
        this.set_message ("your score : " + (this.get_score).ToString() )
        do! _gameAwaiter.Delay(float 4000) |> Async.AwaitTask
    }

  override this.LoadContent() =
    base.LoadContent()
    this.StartMenu() |> Async.StartImmediate 

Fine, but how does it work? All I had to do was to implement class GameAwaiter deriving from GameComponent which means that we can add it to the components stored inside Game class and its Update method will be called automatically when Game’s Update method is being called. GameAwaiter gives us basically a few public methods such as Gesture, Delay and WhenAny. All of them return Task object which means that at some point in the future the result will come. Let’s see the details:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;

namespace AsyncXnaIntegration
{
    using AsyncXnaIntegration;

    public class GameAwaiter : GameComponent
    {
        private readonly List<Job> _jobs = new List<Job>();

        public GameAwaiter(Game game)
            : base(game)
        { }

        public Task Delay(TimeSpan interval)
        {
            return RegisterJob(new TimerJob { Interval = interval });
        }
        
        public Task Delay()
        {
            return RegisterJob(new TimerJob());
        }
     
        public Task While(Func<bool> condition)
        {
            return RegisterJob(new WhileJob { Condition = condition });
        }
  
        public Task<GestureSample[]> Gesture(Func<GestureSample, bool> predicate)
        {
            return RegisterJob(new GestureJob { GestureCondition = predicate });
        }

        public void TryDisposeTask(Task tt)
        {
            var job = _jobs.FirstOrDefault(j => j.TaskO == tt);
            if (job != null)
                job.IsDisposed = true;
        }

        public override void Update(GameTime gametime)
        {
            var state = new State { GameTime = gametime, TouchState = TouchPanel.GetState(), };
            while (TouchPanel.IsGestureAvailable)
                state.Gestures.Add(TouchPanel.ReadGesture());

            foreach (var job in _jobs.ToArray())
            {      
                if (job.IsDisposed || job.Update(state))                
                    _jobs.Remove(job);
            }
        }


        private Task<T> RegisterJob<T>(Job<T> job)
        {
            _jobs.Add(job);
            return job.Task;
        }

        #region inner types

        private class State
        {
            public GameTime GameTime;
            public TouchCollection TouchState;
            public readonly List<GestureSample> Gestures = new List<GestureSample>();
        }

        private abstract class Job
        {
            public bool IsDisposed { get; set; }
            public abstract Task TaskO { get; }

            public abstract bool Update(State state);
        }

        private abstract class Job<T> : Job
        {
            protected TaskCompletionSource<T> _source = new TaskCompletionSource<T>();
            public Task<T> Task { get { return _source.Task; } }
            public override Task TaskO { get { return Task; } }
        }

        private class TimerJob : Job<object>
        {
            private TimeSpan? StartTime;
            public TimeSpan? Interval;

            public override bool Update(State state)
            {
                if (!Interval.HasValue)
                {
                    _source.TrySetResult(null);
                    return true;
                }

                if (!StartTime.HasValue)
                    StartTime = state.GameTime.TotalGameTime;

                if (state.GameTime.TotalGameTime - StartTime >= Interval)
                {
                    _source.TrySetResult(null);
                    return true;
                }

                return false;
            }
        }

        private class WhileJob : Job<object>
        {
            public Func<bool> Condition;

            public override bool Update(State state)
            {
                if (Condition())
                {
                    _source.TrySetResult(null);
                    return true;
                }
                return false;
            }
        }

        private class GestureJob : Job<GestureSample[]>
        {
            public Func<GestureSample, bool> GestureCondition;

            public override bool Update(State state)
            {
                if (state.Gestures.Count > 0)
                {
                    if (GestureCondition == null)
                    {
                        _source.TrySetResult(state.Gestures.ToArray());
                        return true;
                    }

                    var gestures = state.Gestures.Where(GestureCondition).ToArray();
                    if (gestures.Length > 0)
                    {
                        _source.TrySetResult(gestures);
                        return true;
                    }
                }

                return false;
            }
        }

        #endregion
    
    }


public static class GameAwaiterExtensions
    {
        public static Task<Branch> WhenAny(this GameAwaiter gameAwaiter, params Task[] tasks)
        {
            return GameAwaiterExtensions.WhenAny(tasks)
                .ContinueWith(t =>
                {
                    try
                    {
                        foreach (var tt in tasks)
                            gameAwaiter.TryDisposeTask(tt);
                        return t.Result;
                    }
                    catch (Exception exception)
                    {
                        Debugger.Break();
                        return t.Result;
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);
        }

        public static Task<Branch> WhenAny(params Task[] tasks)
        {
            return TaskEx
                .WhenAny(tasks)
                .ContinueWith(t =>
                {
                    var task = t.Result;
                    var taskType = task.GetType();
                    object value = null;

                    // we cannot read nonpublic types via reflection in silverlight 
                    if (taskType.IsGenericType && taskType.GetGenericArguments()[0].IsPublic)
                        value = task.GetType().GetProperty("Result").GetValue(task, null);

                    return new Branch { Index = Array.IndexOf(tasks, task), Value = value };                    
                }, TaskContinuationOptions.ExecuteSynchronously);
        }

        public static Task Delay(this GameAwaiter gameAwaiter, double milliseconds)
        {
            return gameAwaiter.Delay(TimeSpan.FromMilliseconds(milliseconds));
        }

        public static Task<GestureSample[]> Gesture(this GameAwaiter gameAwaiter, GestureType gestureType)
        {
            return gameAwaiter.Gesture(g => (g.GestureType & gestureType) == gestureType);
        }

        public static  Task<GestureSample[]> Gesture(this GameAwaiter gameAwaiter)
        {
            return gameAwaiter.Gesture(g => true);
        }
    }


    public class Branch
    {
        public int Index;
        public object Value;
    }
}

The last thing I would like to mention is a really tricky stuff :) What was really important for me when writing GameAwaiter, was the linear execution of the code. I didn’t want to introduce any new threads or use the SynchronizationContext object underneath. XNA framework calls Update and Draw methods one by one in the single thread many times per second and next iteration can start after the previous one has finished, so it’s really easy to debug such a single-threaded application. The problem is that, by default, Async CTP uses SynchronizationContext‘s Post method when the continuation delegate passed to TaskAwaiter object is called. Of course that happens if any context exists and in XNA case the “SynchronizationContext.Current” property returns the instance of the context. The latest version of Async CTP gives us the ability to configure that behavior but we would need to call “task.ConfigureAwait(false)” in every place where we use await keyword. That would be pretty inconvenient. So I have implemented my own extension method for Task object, that creates appropriately configured awaiter object.

namespace AsyncXnaIntegration
{    
    public static class Extensions
    {
        public static ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter(this Task task)
        {
            return task.ConfigureAwait(false).GetAwaiter();
        }

        public static ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter GetAwaiter<T>(this Task<T> task)
        {
            return task.ConfigureAwait(false).GetAwaiter();
        }
    }
}

Now we need to find a way to force C# compiler to use our extension method instead of that provided in AsyncCtpLibrary_Phone.dll library. We can do it for example by placing “using AsyncXnaIntegration;” statement inside the namespace declaration in all files where we are using Async CTP. Thanks to that little trick our method will be “closer” than all others defined outside the namespace declaration.

Of course GameAwaiter class can be extended (and it most likely will be) by many other useful methods simplifying use of phone’s Keyboard, Geo-Position or Accelerometer APIs, but this is just a proof of concept. As always I encourage you to download the source code and definitely play the Smiley game :) Thanks for reading this post and I hope it will open your eyes for many new very interesting scenarios where the Async CTP can change XNA game development.

downlaod

Friday, January 21, 2011

Async CTP on WP7

In this post I will show you how to use Async CTP released during last PDC conference inside your Windows Phone application. Async CTP extends two .Net platform languages C# and VB giving us a new way of writing asynchronous code. There are two main aspects of this project: new C#/VB compiler (two new keywords: async, await) and library AsyncCtpLibrary.dll. When the compiler sees asynchronous method it generates IL code (which we will see in details further) and that code is using some types from the mentioned library. The problem is that so far we have only two versions of library: .Net and Silverlight. So in this post I will show you how we can use  Async CTP on Windows Phone 7 despite these limitations.

The first thing we need to do before we write our first asynchronous method in the WP7 project is we need to add the reference to Silverlight version of the library AsyncCtpLibrary_Silverlight.dll. Just after doing it Visual Studio shows  a warning: “Adding a reference to a Silverlight assembly may lead to unexpected application behavior. Do you want to continue?”. The problem is that the assembly is compiled under full version of Silverlight and the Windows Phone does not contain the full version but some subset of it running on the top of .Net compact framework. So if we execute some code from such a assembly which is using types that are not available on the phone we will get the runtime exception. The key element of the AsyncCtpLibrary are Tasks and unfortunately they are not running on the phone throwing exception at runtime. The question is: can we use Async CTP without Tasks ? Of course we can! The whole mechanism behind asynchronous methods doesn’t force us to use the instance of type Task followed by await keyword. That type needs to contain method (instance or extension method) called GetAwaiter returning any type that contains appropriate pair of methods (instance or extension) BeginAwait and EndAwait. And all I did is I implemented such a matching type.

public enum AwaiterResultType
{
    Completed,
    Failed,
    Cancelled
}

public class AwaiterResult<T>
{
    public AwaiterResultType ResultType { get; private set; }
    public Exception Exception { get; private set; }
    public T Value { get; private set; }

    private AwaiterResult() { }
    public static AwaiterResult<T> Completed(T result)
    {
        return new AwaiterResult<T> { ResultType = AwaiterResultType.Completed, Value = result };
    }
    public static AwaiterResult<T> Failed(Exception exception)
    {
        return new AwaiterResult<T> { ResultType = AwaiterResultType.Failed, Exception = exception };
    }
    public static AwaiterResult<T> Cancelled()
    {
        return new AwaiterResult<T> { ResultType = AwaiterResultType.Cancelled };
    }
}

public class Awaiter<T>
{
    private SynchronizationContext Context { get; set; }
    private bool IsSynchronized { get; set; }
    private Action _continuation;

    public AwaiterResult<T> Result { get; private set; }

    private Awaiter() { }

    public Awaiter<T> GetAwaiter()
    {
        return this;
    }

    public bool BeginAwait(Action continuation)
    {
        if (Result != null)
            return false;

        _continuation += continuation;
        return true;
    }

    public T EndAwait()
    {
        if (Result == null)
            throw new InvalidOperationException("Awaiter does not contain the result yet.");

        if (Result.ResultType == AwaiterResultType.Completed)
            return Result.Value;

        if (Result.ResultType == AwaiterResultType.Failed)
            throw Result.Exception;

        return default(T); // if cancelled
    }

    private void OnResult(AwaiterResult<T> result)
    {
        if (result == null) throw new ArgumentNullException("result");
        if (Result != null) throw new InvalidOperationException("The result can be provided only once.");

        Result = result;
        if (IsSynchronized && Context != null)
        {
            Context.Post(o =>
                             {
                                 if (_continuation != null)
                                     _continuation();
                                 _continuation = null;
                             }, null);
            Context = null;
        }
        else
        {
            if (_continuation != null)
                _continuation();
            _continuation = null;
        }
    }

    public static Awaiter<T> Create(Action<Action<AwaiterResult<T>>> resultProvider, bool synchronizeWithCurrentContext = true)
    {
        if (resultProvider == null) throw new ArgumentNullException("resultProvider");

        var awaiter = new Awaiter<T> { IsSynchronized = synchronizeWithCurrentContext };
        if (synchronizeWithCurrentContext)
            awaiter.Context = SynchronizationContext.Current;
        resultProvider(awaiter.OnResult);
        return awaiter;
    }
}

The key class here is Awaiter class containing appropriate three methods: GetAwaiter, BeginAwait and EndAwait. This is an abstraction of asynchronous work (very similar to Task type) which at some point in time is finishing its work in one of three possible states: an exception could be thrown, maybe someone cancelled the execution or the work has been completed correctly returning some result. The constructor is private so the factory method called Create is the only way to create an instance of Awaiter type. So let’s see how we can use it:

public static class AwaiterEx
{
    public static Awaiter<T> Run<T>(Func<T> action)
    {
        return Awaiter<T>.Create(resultProvider =>
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                try
                {
                    var result = action();
                    resultProvider(AwaiterResult<T>.Completed(result));
                }
                catch (Exception exception)
                {
                    resultProvider(AwaiterResult<T>.Failed(exception));
                }
            },null);
        });         
    }

    public static Awaiter<object> Delay(TimeSpan timeSpan)
    {
        return Awaiter<object>.Create(resultProvider =>
        {
            var timer = new Timer(o => resultProvider(AwaiterResult<object>.Completed(null)));
            timer.Change((int)timeSpan.TotalMilliseconds, -1);
        });
    }
}

async private static void Sample()
{
    int intResult = await AwaiterEx.Run(() =>
    {
        Thread.Sleep(3000);
        return 123;
    });
    MessageBox.Show("Completed: " + intResult);

    await AwaiterEx.Delay(TimeSpan.FromSeconds(3));
    MessageBox.Show("After 3 seconds...");
}

Now let’s look at simplified version of what compiler is generating underneath to allow us to write synchronously looking code running asynchronously.

private static void SampleInternals()
{
    Awaiter<int> awaiter1 = null;
    Awaiter<object> awaiter2 = null;
    int state = 0;
    
    Action action = null;
    action = () =>
    {
        if (state == 1) goto JUMP_LABEL_1;
        if (state == 2) goto JUMP_LABEL_2;
        
        awaiter1 = AwaiterEx.Run(() =>
        {
            Thread.Sleep(3000);
            return 123;
        }).GetAwaiter();
        state = 1;
        
        if (awaiter1.BeginAwait(action))
            return;
        
        JUMP_LABEL_1:
        var intResult = awaiter1.EndAwait();
        MessageBox.Show("Completed: " + intResult);


        awaiter2 = AwaiterEx.Delay(TimeSpan.FromSeconds(3)).GetAwaiter();
        state = 2;

        if (awaiter2.BeginAwait(action))
            return;

        JUMP_LABEL_2:
        awaiter2.EndAwait();
        
        MessageBox.Show("After 3 seconds...");
    };

    action();         
}

The last thing worth mentioning is how to write asynchronous method returning some value. Asynchronous methods have two limitations: void, Task and Task<T> are the only valid return types and out parameters are not allowed. As we said before Tasks under WP7 don’t work so we cannot return Task object. In fact the solution is very simple:

public static class AwaiterEx
{
    public static Awaiter<object> BeginWriteAwaiter(this Stream stream, byte[] buffer, int offset, int numBytes)
    {
        return Awaiter<object>.Create(resultProvider =>
        {
            try
            {
                stream.BeginWrite(buffer, offset, numBytes, o =>
                {
                    try
                    {
                        stream.EndWrite(o);
                        resultProvider(AwaiterResult<object>.Completed(null));
                    }
                    catch (Exception exception)
                    {
                        resultProvider(AwaiterResult<object>.Failed(exception));
                    }
                }, null);
            }
            catch (Exception exception)
            {
                resultProvider(AwaiterResult<object>.Failed(exception));
            }
        });
    }
}

public Awaiter<object> WriteFileAwaiter(string path, string text)
{
    return Awaiter<object>.Create(async resultProvider =>
    {
        try
        {
            using (var stream = IsolatedStorageFile.OpenFile(path, FileMode.Create))  
                // caution: in fact the stream is running synchronously on WP7
            {
                var data = Encoding.Unicode.GetBytes(text);
                await stream.BeginWriteAwaiter(data, 0, data.Length);
                resultProvider(AwaiterResult<object>.Completed(null));
            }
        }
        catch (Exception exception)
        {
            resultProvider(AwaiterResult<object>.Failed(exception));
        }
    });
}

I encourage you to download sources with attached samples and play with Async CTP on WP7 because it changes a lot in terms of writing asynchronous code. AsyncCtpLibrary library provides TaskEx class with few very useful methods so you can find counterpart in my library called AwaiterEx with following API:

public static class AwaiterEx
{
    public static Awaiter<string> DownloadStringAwaiter(this WebClient webClient, Uri uri) { ... }
    public static Awaiter<object> BeginWriteAwaiter(this Stream stream, byte[] buffer, int offset, int numBytes) { ... }
  
    public static Awaiter<T> ToAwaiter<T>(this IObservable<T> observable) { ... }
    public static Awaiter<T[]> ToAwaiterAll<T>(this IObservable<T> observable) { ... }
    public static IObservable<T> ToObservable<T>(this Awaiter<T> awaiter) { ... }
    
    public static Awaiter<T[]> WhenAll<T>(this IEnumerable<Awaiter<T>> awaiters) { ... }
    public static Awaiter<T[]> WhenAll<T>(params Awaiter<T>[] awaiters) { ... }
    public static Awaiter<T> Run<T>(Func<T> action) { ... }
    public static Awaiter<object> Delay(TimeSpan timeSpan) { ... }
}

Have fun and let me know if you liked it or not. Download