Proto.Actor first look

No sooner had I started looking to use Akka.net, than I find out about Proto.Actor (via .NET Rocks). From my understanding this comes from some of the same guys involved in Akka.net and currently supports .NET and the language Go.

One of my previous posts covered Getting started with Akka.net. Let’s take that post and rewrite the code using the Proto.Actor library, just to see what the differences are.

  • Create a Console application
  • Using Nuget, add the Proto.Actor package
  • Create a class named Greet, this will be used as the payload for wrapping our data that we shall pass to our Actor object. Here’s the code
    public class Greet
    {
       public Greet(string who)
       {
          Who = who;
       }
     
       public string Who { get; private set; }
    }
    
  • Create a new class named GreetingActor. This is our Actor object that does something and will accept objects of type Greet, the code should look like this
    public class GreetingActor : IActor
    {
       public Task ReceiveAsync(IContext context)
       {
          var greet = context.Message as Greet;
          if (greet != null)
          {
             Console.WriteLine("[Thread {0}] Greeting {1}",
                    Thread.CurrentThread.ManagedThreadId,
                    greet.Who);
          }
          return Actor.Done;
       }
    }
    

    So here’s the first difference, code-wise. We are implementing the IActor interface and our code goes in the ReceiveAsync method as opposed the Akka.net code which went in the constructor. Also we have to check the type in the context Message as opposed to using the Akka.net Receive<> generic to differentiate our types. Obviously with the latest C# 7 features we can use type matching, but I’m running this on C# 6 so the standard as operator is used.

  • Finally we want to create an instance of an actor and send a message to it via the Tell method, so our Main method should look like this
    var props = Actor.FromProducer(() => new GreetingActor());
    var greeter = Actor.Spawn(props);
    greeter.Tell(new Greet("Hello World"));
    
    // to stop the console closing 
    // before the message is received
    Console.ReadLine();
    

    This differs from Akka.net in the way we create the greeter but it’s the same number of lines of code and equally simple.

So in the code above we create the Greet class for our message type (in essence) and obviously the GreetingActor listens for Greet messages. In the Main method we create a Props instance from the Actor system using FromProducer (which acts as a factory type pattern) then using the Actor.Spawn we actually create an instance of each actor we want in our system.

The Tell line in the Main method is the same as Akka.net, in that we send a message to the greeter Actor via the Tell method and at some point the GreatingActor will receive this message and write it’s text to the Console and that’s it.