A Look at ETW – Part 3

In part two of this series on Event Tracing for Windows I wrote a simple EventSource to provide strongly-typed events with Entity Framework interceptors. After playing around with ETW a bit more, and still frustrated by the documentation, I decided to switch gears and do something fun, so here in part 3 I’ll try using ETW in an AOP solution.

AOP is of course a great fit for a cross-cutting concern like logging or tracing, and my AOP framework of choice, PostSharp, actually already has a Diagnostics Pattern Library which supports logging to trace, the console, NLog, Log4Net and the Enterprise Library Logging Application Block, but since there’s no built-in support for ETW I’ll get to write my own aspect.

In addition to using AOP for method entry-exit tracing, I also like how tools such as Azure Application Insights and Xamarin Insights make it easy to wrap a block of code in a using statement for tracing purposes, and want to do something similar with ETW. E.g., in Xamarin Insights:

    using (var handle = Insights.TrackTime("something")) {
       .. stuff to track
    }

Since I want to reuse these features I’ll bundle this up in a .NET library, and because naming things continues to be really hard, call it “SampleAnalytics”. The only dependencies are the NuGet packages for Microsoft.Diagnostics.Tracing.EventSource and PostSharp.

The EventSource

Although a strength of ETW is its strongly-typed events, after seeing several examples which use more “generic” events yet still benefit from ETW and its tooling, I’m going to try that and go with a few general-purpose events.

Several of the logging frameworks use the concept of “category” (or a dictionary of categories), so I’ve decided that might be useful here too. Since I want to trace both methods and code blocks I use “Action” and “actionName” to designate either. I also want to make timing optional: ETW events have a high-resolution timestamp and some tools will pair up start/stop events, so doing my own timing isn’t always necessary. If there’s no listener on my ETW events it’s also inefficient.

So the EventSource starts taking shape.

[EventSource(Name = "Samples-Analytics")]
public sealed class AnalyticsEventSource : EventSource {

  public static readonly AnalyticsEventSource Log = new AnalyticsEventSource();

  public class Tasks {
    public const EventTask TimedAction = (EventTask)0x1;
    public const EventTask Action = (EventTask)0x2;
  }

  private const int TraceActionTimedStartEventId = 1;
  private const int TraceActionTimedStopEventId = 2;
  private const int TraceActionStartEventId = 3;
  private const int TraceActionStopEventId = 4;

  [Event(TraceActionTimedStartEventId, Level = EventLevel.Verbose, Task = Tasks.TimedAction, Opcode = EventOpcode.Start)]
  public void TraceActionTimedStart(string category, string actionName) {
    WriteEvent(TraceActionTimedStartEventId, category, actionName);
  }

  [Event(TraceActionTimedStopEventId, Message = "Category '{0}' - Action '{1}' took {2} ms", Level = EventLevel.Verbose, Task = Tasks.TimedAction, Opcode = EventOpcode.Stop)]
  public void TraceActionTimedStop(string category, string actionName, long elapsedMilliseconds) {
    WriteEvent(TraceActionTimedStopEventId, category, actionName, elapsedMilliseconds);
  }

  [Event(TraceActionStartEventId, Level = EventLevel.Verbose, Task = Tasks.Action, Opcode = EventOpcode.Start)]
  public void TraceActionStart(string category, string actionName) {
    WriteEvent(TraceActionStartEventId, category, actionName);
  }

  [Event(TraceActionStopEventId, Level = EventLevel.Verbose, Task = Tasks.Action, Opcode = EventOpcode.Stop)]
  public void TraceActionStop(string category, string actionName) {
    WriteEvent(TraceActionStopEventId, category, actionName);
  }
}

This wasn’t quite as simple as it appears, since I found that an overload for WriteEvent(int, string, string, long) doesn’t exist in the base EventSource and needed to write it myself. This involved pointers and unsafe code, and the curious can see the code download for details.

Tracing code blocks

I’ll be doing tracing of both timed and untimed “actions”, so define a disposable TraceAction and TimedAction.

public interface ITraceAction : IDisposable {
  void Start();
  void Stop();
}

Untimed actions generate start and stop events:

public class TraceAction : ITraceAction {

  private readonly string _category;
  private readonly string _actionName;

  internal TraceAction(string category, string actionName) {
    _category = category;
    _actionName = actionName;
  }

  public void Start() {
    AnalyticsEventSource.Log.TraceActionStart(_category, _actionName);
  }

  public void Stop() {
    AnalyticsEventSource.Log.TraceActionStop(_category, _actionName);
  }

  public void Dispose() {
    Stop();
  }
}

While timed actions also use a Stopwatch:

public class TimedAction : ITraceAction {

  private readonly string _category;
  private readonly string _actionName;
  private Stopwatch _stopwatch;

  internal TimedAction(string category, string actionName) {
    _category = category;
    _actionName = actionName;
  }

  public void Start() {
    AnalyticsEventSource.Log.TraceActionTimedStart(_category, _actionName);
    _stopwatch = Stopwatch.StartNew();
  }

  public void Stop() {
    if (_stopwatch == null || !_stopwatch.IsRunning) return;
    _stopwatch.Stop();
    AnalyticsEventSource.Log.TraceActionTimedStop(_category, _actionName, _stopwatch.ElapsedMilliseconds);
  }

  public void Dispose() {
    Stop();
  }
}

Along with a helper class…

public static class Analytics {

  public static ITraceAction TrackTime(string actionName, string category = "Trace") {
    var action = new TimedAction(category, actionName);
    action.Start();
    return action;
  }

  public static ITraceAction TrackUntimed(string actionName, string category = "Trace") {
    var action = new TraceAction(category, actionName);
    action.Start();
    return action;
  }
}

 
With these in place I can now trace a block of code like this:

using (var timedAction = Analytics.TrackTime("Save Student")) {
  db.SaveChanges();
}

For method-level interception I’ll need AOP.

Tracing methods

PostSharp provides method interception with the OnMethodBoundaryAspect. They have a good amount of documentation showing how to use it so it’s very easy to get started. All that’s necessary is to sub-class the aspect and override any needed interception points:

public class SomeCustomAttribute : OnMethodBoundaryAspect {
 public override void OnEntry(MethodExecutionArgs args) ..
 public override void OnExit(MethodExecutionArgs args) ..
 public override void OnSuccess(MethodExecutionArgs args) ..
 public override void OnException(MethodExecutionArgs args) ..
 public override void OnYield(MethodExecutionArgs args) ..
 public override void OnResume(MethodExecutionArgs args) ..
}

OnEntry, OnExit, OnSuccess and OnException are self-explanatory; OnYield and OnResume allow for more accurate interception of async code.

MethodExecutionArgs give you access to the method name, any argument types and values, the exception thrown and any return value. The class also has a handy Tag property which allows you to plug in any user-defined object for the duration of the method call.

OnMethodBoundaryAspect also has built-in multicasting, so when you apply your attribute to a class or an assembly all methods in that class or assembly will be intercepted. Since this can be quite a bit more than you want (especially if you don’t want to intercept things like getters and setters, ToString, GetHashCode, etc.) there are also a number of attributes available to control this.

I still want to use a “category” to help apply some semantic information to events, and timing should be optional here too. Both parameters can be set when the attribute is applied.

[Serializable]
public class ETWTraceAttribute : OnMethodBoundaryAspect {

  private string _methodName;
  private string _category;
  private bool _addTiming;

  public ETWTraceAttribute(string category = "default", bool addTiming = false) {
    ApplyToStateMachine = true;
    _category = category;
    _addTiming = addTiming;
  }

For example, applied to a method:

[ETWTrace(category: "Instructor")]
public ActionResult Index(int? id, int? courseID) {..}

And applied to a class:

[ETWTrace(category: "Course", addTiming: true)]
public class CourseController : Controller {..}

 
I’ll also grab the method information at compile-time rather than run-time, as it’s more efficient. I could have grabbed parameter and generic arguments too, but I’m not sure that the extra information will help when doing an ETW analysis so I’ve left them out for now:

  public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) {
    _methodName = method.DeclaringType.FullName + "." + method.Name;
  }

At run-time, tracing should start when the method starts. The parameter values are available here too, but since the ETW event won’t be enabled without a listener I don’t want to incur any performance penalty in getting their string representation. The TrackTime and TrackUntimed helper methods defined above can be used here too, and the ITraceAction stashed within the MethodExecutionTag for later use.

public override void OnEntry(MethodExecutionArgs args) {
  var action = _addTiming ? Analytics.TrackTime(_methodName, _category)
                          : Analytics.TrackUntimed(_methodName, _category);
  args.MethodExecutionTag = action;
}

When the method completes successfully I’ll stop tracing. The method return value is available here also, but again, I don’t want to include it in the ETW event:

public override void OnSuccess(MethodExecutionArgs args) {
  var action = args.MethodExecutionTag as ITraceAction;
  action.Stop();
}

So that’s nearly all there is to it. It’s not as full-featured as PostSharp’s Diagnostic Library, but it’s a start. I did add OnException, OnYield and OnResume handling too; those are available in the source code download.

With a few simple changes to the ContosoUniversity sample application from part 2, a PerfView trace now shows both method-level and code block tracing:

traceactivity1

Logging to an interface

Now that the ContosoUniversity sample is using the “SampleAnalytics” library it no longer needs its own EventSource too. In the spirit of more “generic” events, and finding that an EventSource can implement an interface, I’m going to remove all the logging I added in part 2 and have the interceptors use a simple logging interface:

public interface ILogger {
  void TraceInformation(string message, string category = null, string subcategory = null);
  void TraceWarning(string message, string category = null, string subcategory = null);
  void TraceError(string message, string category = null, string subcategory = null);
}

“Category” and “sub-category” will allow the ETW events to provide a bit more than printf-style logging.

Here’s the DbCommandInterceptor using ILogger, with a category of “Command” and a sub-category set to the calling method name via the CallerMemberName attribute.

public class SchoolInterceptorLogging : DbCommandInterceptor {

  private const string Category = "Command";
  private ILogger _logger; 

  public SchoolInterceptorLogging(ILogger logger) {
    _logger = logger;
  }

  public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) {
    LogTraceOrException(command);
  }

  public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) {
    LogTraceOrException(command, interceptionContext.Exception);
  }

  ... and so on for NonQuery and Reader command types

  private void LogTraceOrException(DbCommand command, Exception exception = null, [CallerMemberName] string methodName = "") {
    if (exception == null) {
      _logger.TraceInformation(command.CommandText, Category, methodName);
    } else {
      _logger.TraceError(exception.Message, Category, methodName);
    }
}

With similar changes for the IDbConnectionInterceptor:

public class SchoolConnectionInterceptor : IDbConnectionInterceptor {

  private const string Category = "Connection";
  private ILogger _logger; 

  public SchoolConnectionInterceptor(ILogger logger) {
    _logger = logger;
  }

  public void Opening(DbConnection connection, DbConnectionInterceptionContext interceptionContext) {
    LogTraceOrException(connection, interceptionContext);
  }

  public void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext) {
    LogTraceOrException(connection, interceptionContext);
  }

  private void LogTraceOrException(DbConnection connection, DbConnectionInterceptionContext context, [CallerMemberName] string methodName = "") {
    if (context.Exception == null) {
      _logger.TraceInformation(connection.Database, Category, methodName);
    } else {
      _logger.TraceError(context.Exception.Message, Category, methodName);
    }
}

The EventSource can now implement ILogger, along with the other trace events shown earlier:

[EventSource(Name = "Samples-Analytics")]
public sealed class AnalyticsEventSource : EventSource, ILogger {

    ... 

    private const int TraceInformationEventId = 5;
    private const int TraceWarningEventId = 6;
    private const int TraceErrorEventId = 7;

    ...

    [Event(TraceInformationEventId, Level = EventLevel.Informational)]
    public void TraceInformation(string message, string category = "", string subcategory = "") {
      WriteEvent(TraceInformationEventId, message, category, subcategory);
    }

    [Event(TraceWarningEventId, Level = EventLevel.Warning)]
    public void TraceWarning(string message, string category = "", string subcategory = "") {
      WriteEvent(TraceWarningEventId, message, category, subcategory);
    }

    [Event(TraceErrorEventId, Level = EventLevel.Error)]
    public void TraceError(string message, string category = "", string subcategory = "") {
      WriteEvent(TraceErrorEventId, message, category, subcategory);
    }
}

 
And finally, a PerfView collection now shows the traced actions along with other activity from the interceptors:

traceactivity3

A zip of the modified sample application and “SampleAnalytics” library is available here. Source for the SampleAnalytics library only is also available on github.

Advertisements

PostSharpin’ – Part 3

In the final part of this series I look at new features coming in PostSharp 3.2, including support for aggregates and undo/redo.

Aggregates

Under the hood, the biggest new feature in 3.2 might be the support for aggregates: object graphs with parent-child relationships. Version 3.2 makes aggregates first class citizens in the world of PostSharp aspects, and allows PostSharp to offer more complex features like undo/redo. They’ve also modified other aspects to be aggregate aware – so for example the Actor aspect now also implements IAggregatable.

You mark up properties in your aggregatable types with Child, Parent and Reference aspects, and PostSharp then does the right thing when dealing with your object graph. I mentioned an “aggregatable type” – you can mark up your class with the Aggregatable aspect, but on its on this won’t do much. Instead you’ll use another instance-level aspect – such as Recordable, Immutable, Disposable, and others – which are all aggregate aware and will work correctly with your object graph.

If you’re using Entity Framework, nHibernate, or similar, these frameworks already understand your graph and its relationships, so additional markup may feel like more work, although these aspects could open the door to custom aspects which understand both the data services layer and composition of your model.

Here’s a simple example of aggregates with the new Disposable aspect, which handles the dirty work of implementing IDisposable on types in your graph.

using PostSharp.Patterns.Collections;
using PostSharp.Patterns.Model;

[Disposable]
public class Order
{
    public Order()
    {
        Details = new AdvisableCollection<OrderDetail>();
    }

    public int Id { get; set; }
    public DateTime OrderDate { get; set; }
    public string Customer { get; set; }
    
    [Child]
    public ICollection<OrderDetail> Details { get; private set; }
}

[Disposable]
public class OrderDetail
{
    public int Id { get; set; }
    public string Product { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
} 

The child collection must be of type AdvisableCollection, otherwise PostSharp raises a runtime error. But once defined correctly, when the parent is disposed PostSharp will dispose of all children too.

A bit irritating, though, is that to use your parent type in a using statement you must initialize it outside the scope of the using to avoid the build-time error type used in a using statement must be implicitly convertible to System.IDisposable:

var order = new Order { Id = 1, OrderDate = DateTime.Now };
using (order as IDisposable)
{
   ...
}

Immutable and Freezable

I was initially excited to see that PostSharp will be adding Immutable and Freezable aspects in version 3.2.

When you need to support thread-safe access for a number of object types, the idea of immutable types is really appealing. But also attractive is the use of object initializers. Unfortunately, since object initializers require public setters the type can’t be immutable. Named constructor parameters can partially solve the issue, but the brevity of object initializers, for both the caller and callee, can’t be beat. Fortunately, C# 6.0 should make writing immutable types easier with the new primary constructors and property initializers, but I was hoping that PostSharp could work some magic here right now, without having to wait for the C# release. Well, this may be a pipe dream of mine. PostSharp will be adding support for early and late object initialization through Immutable and Freezable, but these address the problem with regard to object graphs and “deep” immutability. Granted, this will be a helpful feature. Unfortunately, I wasn’t able to get these aspects working correctly with the alpha code so I’ll have to try again later.
Edit: Per Gael Fraiteur’s recommendation, an upgrade to version 3.2.20-alpha got this working. As hoped, PostSharp will raise an ObjectReadOnlyException if you try to make any changes to an Immutable type after construction or a Freezable type after Freeze is called. This works for both simple and “deep” fields and properties. I expect “freezability” to be especially useful.

These aspects are available from the pre-release version of the PostSharp Threading Pattern Library. A more thorough discussion of these aspects is available here.

Recordable

Now here is something to get excited about. Implementing the Memento pattern on your own is usually hard, error prone, and non-performant; probably the reason why so few applications and frameworks support it, but also making it a great candidate for an AOP approach.

The Recordable aspect builds upon the support for aggregation, so with a few simple changes to the code above I’m ready for Undo/Redo support:

using PostSharp.Patterns.Collections;
using PostSharp.Patterns.Model;
using PostSharp.Patterns.Recording;

[Recordable]
public class Order
{
    public Order()
    {
        Details = new AdvisableCollection<OrderDetail>();
    }

    public int Id { get; set; }
    public DateTime OrderDate { get; set; }
    public string Customer { get; set; }

    [Child]
    public ICollection<OrderDetail> Details { get; private set; }
}

[Recordable]
public class OrderDetail
{
    public int Id { get; set; }
    public string Product { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
}

As before, the child collection must be an AdvisableCollection, otherwise an error is thrown.

Once a type, or the types in an object graph, are made recordable, you then use the new RecordingServices features. The Recorder tracks operations within a scope and provides undo/redo functions. There’s a default Recorder, RecordingServices.DefaultRecorder, to get started or for simple applications.

By default, every change to a property or field, add/remove from a child collection, or call to a public method on the class, is atomic. To bundle these into a scope – a logical operation – you use a RecordingScope, which can be set either declaratively or programmatically.

For example:

var order = new Order();
using (RecordingScope scope = RecordingServices.DefaultRecorder.OpenScope(RecordingScopeOption.Atomic))
{
    order.Customer = "Bikes R Us";
    order.Id = 1;
    order.OrderDate = DateTime.Now;
}

If Undo were called after the above, the Order object would be returned to its default state after construction.

It’s worth noting that using an object initializer is not an atomic operation. For example the following will undo the last property set operation (the set of OrderDate):

  var order = new Order { Customer = "Bikes R Us", Id = 1, OrderDate = DateTime.Now };
  RecordingServices.DefaultRecorder.Undo();

Also notable is the factoid that constructors do not participate in an operation, even if the constructor sets properties or fields within the class; the object must be initialized before it can be considered recordable.

Along with Undo is of course Redo.

Here we create a new Order and OrderDetail, Undo the add of the detail line to the order, and then immediately have a change of heart and call Redo to restore the added line:

var order = new Order { Customer = "My Grocer", Id = 1, OrderDate = DateTime.Now };
var od = new OrderDetail { Id = 1, Product = "pears", Quantity = 10, UnitPrice = 1.99M };
order.Details.Add(od);
RecordingServices.DefaultRecorder.Undo();
RecordingServices.DefaultRecorder.Redo();

Restore points are supported too:

var order = new Order { Customer = "My Grocer", Id = 1, OrderDate = DateTime.Now };
RecordingServices.DefaultRecorder.Clear();

var token1 = RecordingServices.DefaultRecorder.AddRestorePoint("first");
order.Details.Add(new OrderDetail { Id = 1, Product = "apples", Quantity = 5, UnitPrice = 1.99M });

var token2 = RecordingServices.DefaultRecorder.AddRestorePoint("second");
order.Details.Add(new OrderDetail { Id = 2, Product = "potatoes", Quantity = 10, UnitPrice = .99M });

// Removes detail 2
RecordingServices.DefaultRecorder.UndoTo(token2);

// Removes detail 1
RecordingServices.DefaultRecorder.UndoTo(token1);

You have a great deal of control over the Recorder and other recordable features, and in general the implementation looks full-featured and quite useful. There’s also a series of blog posts on the PostSharp site with more detailed information.

The recordable feature is available in the pre-release version of the PostSharp Model Pattern Library.

PostSharpin’ Part 2 – Actor

In Part 1 I looked at PostSharp’s support for INotifyPropertyChanged, and several handy aspects to help with threading: Background, Dispatch, ThreadUnsafe and ReaderWriterSynchronized. In part 2 I’d planned to look at PostSharp’s Actor support and new features for undo/redo, but life got in the way, so part 2 will cover only the Actor aspect, and part 3 will cover new features in PostSharp 3.2.

Actor

The Actor model hasn’t yet received a lot of attention in the .NET world. The model was first defined in 1973 as a means to model parallel and distributed systems, “a framework for reasoning about concurrency.” The model assumes that “concurrency is hard” and provides an alternative to do-it-yourself threading and locking. It’s built into languages like Erlang and Scala, and there are a number of libraries and frameworks. It’s gotten a recent boost in the .NET world with F# agents, the TPL Dataflow library and Project Orleans.

Conceptually, an actor is a concurrency primitive which can both send and receive messages and create other actors, all completely asynchronous, and thread-safe by design. An actor may or may not hold state, but it is never shared.

Where does PostSharp fit in? Remembering the PostSharp promise: “Eradicate boilerplate. Raise abstraction. Enforce good design.” the PostSharp Actor implementation allows developers to work at the “right” level of abstraction, and provides both build time and run time validation to avoid shared mutable state and ensure that private state is accessed by only a single thread at a time.

To use the Actor aspect, install the Threading Pattern Library package from NuGet.

Ping Pong

I started with the PingPong sample (well, PingPing really) from PostSharp. Here’s the code:

[Actor]
public class Player 
{
    private string name;
    private int counter;

    public Player(string name)
    {
        this.name = name;
    }

    public async Task Ping(Player peer, int countdown)
    {
        Console.WriteLine("{0}.Ping({1}) from thread {2}", this.name, countdown,
                          Thread.CurrentThread.ManagedThreadId);

        if (countdown > 1)
        {
            await peer.Ping(this, countdown - 1);
        }

        this.counter++;
    }

    public async Task GetCounter()
    {
        return this.counter;
    }
}

class Program
{
    static void Main(string[] args)
    {
        AsyncMain().Wait();
        Console.ReadLine();
    }

    private static async Task AsyncMain()
    {
        Console.WriteLine("main thread is {0}", Thread.CurrentThread.ManagedThr

        Player ping = new Player("Sarkozy");
        Player pong = new Player("Hollande");

        Task pingTask = ping.Ping(pong, 10);

        await pingTask;

        Console.WriteLine("{0} Counter={1}", ping, await ping.GetCounter());
        Console.WriteLine("{0} Counter={1}", pong, await pong.GetCounter());
    }
}

Here the Player class is an actor, and decorated with the PostSharp Actor aspect. The “messages” are implied by the Ping and GetCounter async methods. Whether the “message-ness” of the actor model should be abstracted away is certainly a point for discussion, but it does provide for easier programming within an OO language like C#.

From the output we see that 1) activation (construction) is performed on the caller’s thread, 2) the player’s methods are invoked on background threads, and 3) there is no thread affinity.
pingpong_sm

Validation

The compile-time validation performed when using the Actor aspect tries to ensure you do the right thing.

1. All fields must be private, and private state must not be made available to other threads or actors.

If we try to define the name field as public:

[Actor]
public class Player 
{
    public string name;
    private int counter;
    ...
} 

This results in the compiler error: Field Player.name cannot be public because its declaring class Player implements its threading model does not allow it. Apply the [ExplicitlySynchronized] custom attribute to this field to opt out from this rule.

The same holds true of a public property:

[Actor]
public class Player 
{
    ...
    public int Id { get; private set; }
    ...
}

This results in the compile-time error: Method Player cannot return a value or have out/ref parameters because its declaring class derives from Actor and the method can be invoked from outside the actor.

2. All methods must be asynchronous.

To PostSharp this means that method signatures must include the async modifier. If you try to return a Task from a non-async method, something like this:

 public Task<string> SayHello(string greeting)
 {
     return Task.FromResult("You said: '" + greeting + "', I say: Hello!");
 }

You’ll get a compiler error: Method Player cannot return a value or have out/ref parameters because its declaring class derives from Actor and the method can be invoked from outside the actor.

The async rule also means that you must ignore the standard compiler warning about using async when you don’t demonstrably need to, which is why the GetCounter method looks like this:

public async Task<int> GetCounter()
{
    return this.counter;
}

PostSharp will dispatch the method to a background task, so you should ignore the compiler warning: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.

If you remove the async modifier the Actor validation will fail. You can add an await, but it looks silly, and you shouldn’t await Task.FromResult anyway:

public async Task<int> GetCounter()
{
    return await Task.FromResult<int>(this.counter);
}

You can, however, write a synchronous method, which PostSharp will dispatch to a background thread. For example:

public void Ping(Player peer, int countdown)
{
    Console.WriteLine("{0}.Ping from thread {1}", this.name,
                      Thread.CurrentThread.ManagedThreadId);

    if (countdown >= 1)
    {
        peer.Pong(this, countdown - 1);
    }

    this.counter++;
}

This may be a good thing, but also possibly misleading, since at first glance a developer might assume the method is executed synchronously on the current thread.

Rock-Paper-Scissors

Next I tried the “Rock-Paper-Scissors” example as described here.

Here’s my implementation.

namespace Roshambo
{
    public enum Move
    {
        Rock,
        Paper,
        Scissors
    }

    [Actor]
    public class Coordinator
    {
        public async Task Start(Player player1, Player player2, int numberOfThrows)
        {
            Task.WaitAll(player1.Start(), Task.Delay(10), player2.Start());

            while (numberOfThrows-- > 0)
            {
                var move1Task = player1.Throw();
                var move2Task = player2.Throw();
                Task.WaitAll(move1Task, move2Task);

                var move1 = move1Task.Result;
                var move2 = move2Task.Result;

                if (Tie(move1, move2))
                {
                    Console.WriteLine("Player1: {0}, Player2: {1} - Tie!", move1, move2);
                }
                else
                {
                    Console.WriteLine("Player1: {0}, Player2: {1} - Player{2} wins!", move1, move2,
                        FirstWins(move1, move2) ? "1" : "2");
                }
            }
        }

        private bool Tie (Move m1, Move m2) {
            return m1 == m2;
        }

        private bool FirstWins(Move m1, Move m2)
        {
            return
              (m1 == Move.Rock && m2 == Move.Scissors) ||
              (m1 == Move.Paper && m2 == Move.Rock) ||
              (m1 == Move.Scissors && m2 == Move.Paper);
        }

    }

    [Actor]
    public class Player
    {
        private Random _random;
        private string _name;

        public Player(string name)
        {
            _name = name;
        }
        public async Task Start()
        {
            int seed = Environment.TickCount + System.Threading.Thread.CurrentThread.ManagedThreadId;
            _random = new Random(seed);
        }

        public async Task<Move> Throw()
        {
            return (Move)_random.Next(3);
        }

        public async Task<string> GetName()
        {
            return _name;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        AsyncMain().Wait();
        Console.ReadLine();
    }

    private static async Task AsyncMain()
    {
        var coordinator = new Coordinator();
        var player1 = new Player("adam");
        var player2 = new Player("zoe");

        await coordinator.Start(player1, player2, 20);
    }
}

And the exciting results:
rps

A few things to note:

  • I passed a name to the Player constructor but then never used it again. As private state, to access the name you must follow the Actor message rules and use an async method. I wouldn’t want the Coordinator to repeatedly ask each Player for its name, but this could have been done once at play start.
  • Trying to uniquely seed a System.Random instance for each player was tricky, and my implementation is a hack. The Random class is not thread-safe, so while sharing a single static Random instance among Player actors is an option, having to perform my own locking around Random.Next calls seemed to violate the spirit of the actor model. The default seed for a Random instance is Environment.TickCount, which if called in close succession will likely return the same value. Using the current thread id as a seed is an alternative, but although PostSharp will ensure that Actor methods will be called on a background thread, there’s no assurance they’ll be different threads for different actor instances. My not-so-robust compromise was to take the sum of TickCount and thread id and cross my fingers. Including the dummy Task.Delay when waiting for the players to start helps.
  • The Coordinator here does not hold state, and its Start method will 1) tell the players to start, 2) tell the players to throw, and 3) announce the result.
  • The Player does hold non-shared state, and contains Start, Throw and GetName async methods. None of these methods is inherently asynchronous, so I see compiler warnings telling me to consider using the await operator. I could have made these methods synchronous, but as I said above I think it leads to some cognitive dissonance between the code you see and the underlying actor implementation.

Summary

Overall, despite some quirks, using the Actor aspect could be useful. It would be interesting to compare PostSharp’s Actor support with other .NET implementations, and I may try that some day.

PostSharpin’ – Part 1

I’ve been intrigued with PostSharp for some time. PostSharp is an AOP platform and works its magic at build time (for the most part). You apply an aspect and PostSharp does the IL weaving, via integration with MSBuild, to output an assembly with the injected functionality. The goal, as their home page banner says: “Eradicate boilerplate. Raise abstraction. Enforce good design.”

I worked on the DevForce framework for a number of years and we’d written several custom aspects to implement certain product features, but I’d never had a chance to play with some of the “ready-made” implementations in the PostSharp patterns library. Writing your own aspects can range from fairly easy to quite hard, but many of the out-of-the-box aspects in the patterns library seem to combine great functionality and ease of use. Of particular interest to me are the ready-made patterns for INotifyPropertyChanged support and threading. The patterns library also includes support for logging, exception handling and a few other patterns, but I’ll save those for another day.

To get started with PostSharp, install the package(s) from NuGet. You’ll also be prompted for license information during the install, but since I’m using the 3.2 alpha I signed up for a 45 day free trial of PostSharp Ultimate.

NotifyPropertyChanged

Nothing screams boilerplate more than INotifyPropertyChanged. In any .NET environment, data bound objects must implement INotifyPropertyChanged (or the PropertyChanged pattern) for changes to be seen by UI controls. This means raising the PropertyChanged event, and more importantly, losing the simplicity of automatic properties since property setters must raise PropertyChanged. This gets irritating quickly.

With PostSharp the solution is simple: just decorate the class with the NotifyPropertyChanged aspect, found in the Model Pattern Library.

You can decorate a base class too, and get the functionality you expect across its sub-types. If you’ve both implemented INotifyPropertyChanged and added the aspect (maybe in a complex inheritance hierarchy), PostSharp handles that too. PostSharp will add the PropertyChanged logic to the setters of all public properties, but you can opt-out too by decorating a property with the IgnoreAutoChangeNotification aspect.

Here’s a simple class and sub-class with full INotifyPropertyChanged functionality:

[NotifyPropertyChanged]
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return string.Format("{0} {1}", FirstName, LastName); }
    }

    [IgnoreAutoChangeNotification]
    public DateTime LastContactDate { get; set; }
}

public class GoldCustomer : Customer 
{
     public int Points { get; set; }
}

Under the hood the aspect will inject the INotifyPropertyChanged logic into your IL. Actually, it implements a PostSharp interface called INotifyChildPropertyChanged, which in turn extends INotifyPropertyChanged.

This simplicity does come with a performance penalty, however. In my tests setting a single string property on a class implementing INotifyPropertyChanged (INPC) versus one using the NotifyPropertyChanged aspect, the INPC implementation was about 100x faster. So, while the aspect is a great solution for eliminating the boilerplate, for classes which won’t be data bound in the UI or which have strict performance requirements, it’s not an ideal solution.

Threading

The PostSharp Threading Pattern Library contains several interesting aspects, with more coming in the 3.2 release.

Background and Dispatched

The Background aspect can be applied to any method to dispatch it to the background. Under the hood PostSharp does a Task.Start to invoke your method on a background thread. With the async/await support in .NET 4.5 this may not be all that handy, but if you’re using a BackgroundWorker or working directly with the Thread or ThreadPool classes it may make your code a bit cleaner. Likewise, the Dispatched aspect will ensure the decorated method is invoked on the UI thread. Background and Dispatched don’t need to be used together, and using Dispatched can clean up some ugly BeginInvoke logic.

Coincidentally, I was just reading the April issue of MSDN Magazine and Laurent Bugnion’s article Multithreading and Dispatching in MVVM Applications, so switched his simple non-MVVM starting solution to use Background and Dispatched. Bugnion uses the DispatchHelper from MvvmLight in his MVVM samples; you can use these PostSharp aspects in your view models too, but unlike some of the other PostSharp libraries which have portable class library support, the threading library is available for .NET 4 and above only.

Here’s a snippet of the sample code from the article using Background and Dispatched:

[Background]
private void StartSuccessClick(object sender, RoutedEventArgs e)
{
    // This is a background operation!

    var loopIndex = 0;

    while (_condition)
    {
        // Do something

        // Notify user
        UpdateStatus(string.Format("Loop # {0}", loopIndex++));

        // Sleep for a while
        Thread.Sleep(500);
    }
}

[Dispatched]
private void UpdateStatus(string msg)
{
    StatusTextBlock.Text = msg;
}

These are handy but not all that compelling, since an InvalidOperationException is thrown immediately when you try to access a UI control on a background thread, and therefore easy to diagnose and fix. Much more insidious are thread safety problems. In a multi-threaded environment, safely working with mutable objects can be challenging: thread safety issues generally appear as odd “random” errors and deadlocks, often only under load, and are very difficult to reproduce and debug.

PostSharp defines three threading models or patterns and corresponding aspects: Thread Unsafe, Read-Writer Synchronized and Actor. (I’ll take a look at Actor in a follow-on post.)

ThreadUnsafe
If a single instance of a class should never be accessed concurrently, decorate the class with the ThreadUnsafe aspect. Should you access the object across concurrent threads, you’ll receive an immediate ConcurrentAccessException from PostSharp.

Markup is easy:

[ThreadUnsafe]
public class Booking
{
    public string CustomerName { get; set; }
    public DateTime StartTime { get; set; }
    public int NumberOfPersons { get; set; }
}

The ThreadUnsafe aspect also allows you to set a ThreadUnsafePolicy, such as ThreadAffine, which gives thread affinity to your objects and will cause a ThreadMismatchException to be thrown if the object is used on any thread other than the creating thread. Also baked into ThreadUnsafe is some compile-time validation and support for opting out to perform your own explicit synchronization.

Most classes aren’t designed to be thread safe, and don’t need to be, but if you have any globally shared objects or need to pass an object around among threads, or alternately, ensure it’s never shared across threads, this aspect is far easier to use than performing your own locking. I didn’t look at performance here, but I’ll take a quick exception over data corruption any day.

ReaderWriterSynchronized

Finally, dealing with thread-safe objects. When you do have objects which truly must be shared in a multi-threaded environment dealing with thread safety can be a big pain. First deciding on whether to use a lock, a mutex, a ReaderWriterLock, Interlocked variables, etc., and then what the scope should be. Once it’s finally working correctly a later modification “forgets” to lock the resource, and you don’t discover this until you’re in production under heavy load.

PostSharp handles this declaratively with its ReaderWriterSynchronized aspect. Under the hood it’s an implementation of ReaderWriterSynchronizedSlim, and provides for concurrent reads and exclusive writes. Here you decorate the class with ReaderWriterSynchronized, but must also mark methods, getters and setters with either Reader or Writer aspects. (Prior to PostSharp 3.2 these aspects were called ReaderLock and WriterLock.) The advantage of the aspect, other than the removal of all the locking code, is that PostSharp will immediately detect when a resource is accessed without a lock and throw a LockNotHeldException.

Here’s an example of the .NET sample for a SynchronizedCache using PostSharp aspects:

[ReaderWriterSynchronized]
public class SynchronizedCache
{
    private Dictionary innerCache = new Dictionary();

    [Reader]
    public string Read(int key)
    {
        return innerCache[key];
    }

    [Writer]
    public void Add(int key, string value)
    {
        innerCache.Add(key, value);
    }

    [UpgradeableReader]
    public AddOrUpdateStatus AddOrUpdate(int key, string value)
    {
        string result = null;
        if (innerCache.TryGetValue(key, out result))
        {
            if (result == value)
            {
                return AddOrUpdateStatus.Unchanged;
            }
            else
            {
                innerCache[key] = value;
                return AddOrUpdateStatus.Updated;
            }
        }
        else
        {
            innerCache.Add(key, value);
            return AddOrUpdateStatus.Added;
        }
    }

    [Writer]
    public void Delete(int key)
    {
        innerCache.Remove(key);
    }

    public enum AddOrUpdateStatus
    {
        Added,
        Updated,
        Unchanged
    };
}

In part 2 I plan to take a look at PostSharp’s Actor support, along with the new Recordable aspect for undo/redo and the Immutable and Freezable aspects, available in the upcoming 3.2 release.