How to get started with Akka.Net

Take advantage of Akka.Net to build concurrent, fault tolerant, event-driven applications using the high-level abstractions of the actor model

How to get started with Akka.Net
Thinkstock

Akka.Net is an open source, distributed computing framework built by Petabridge. Akka.Net allows you to create scalable, resilient, concurrent, event-driven applications using the actor model. In this article I will introduce the important concepts behind Akka.Net, discuss why it is useful, and help you get started working with Akka.Net in C#.

The actor model is a programming paradigm that is based on asynchronous, message-driven architecture. In this paradigm, the basic unit of execution is an actor. This programming paradigm is suitable for building large-scale, complex, distributed applications that are highly reliable, but may have unpredictable degrees of latency.

The object-oriented programming approach uses classes and objects to model the problem domain. When working in Akka.Net, you use actors and messages to model your problem. In Akka.Net, an actor is an object with some specific behavior. While actors do have internal state, they don’t have any shared mutable state. You can have many concurrent actors in your application with each of them processing operations independently on their own. Actors are identified by addresses. They derive from the ActorBase class and in turn they can create child actors.

Actors communicate with each other by passing messages asynchronously. Essentially, an actor receives a message and then reacts to it either by processing it or by passing another message to another actor to get the job done. Note that the messages in Akka.Net are processed sequentially, one at a time, in the order in which they arrive. Since actors can be running locally or on a remote server, a common message exchange format is needed. Akka.Net messages are immutable. They can be instances of a string, an integer, or even a custom class.

Let’s look at how we can build a simple actor class and work with messages. First off, you should install Akka.Net from NuGet. You can do this by typing the following command at the NuGet command prompt.

Install-Package Akka

Alternatively, you can install Akka.Net using the NuGet package manager window from within the Visual Studio IDE.

Note that custom actor classes in Akka.Net should derive from the UntypedActor class, which extends the ActorBase class of the Akka.Net framework. Here’s how the structure of a custom actor class in Akka.Net should look.

public class ThisIsACustomActor : UntypedActor
    {
        protected override void PreStart()
        {
            //You can write any initialization code here
        }
        protected override void PreRestart(Exception reason, object message)
        {
        }
        protected override void OnReceive(object message)
        {         
           //This method is used to handle messages
        }
        protected override void PostStop()
        {
            //Here is where you can write the clean-up code.
            //This method gets called when the actor has stopped and is no longer receiving messages
        }
        protected override void PostRestart(Exception reason)
        {
        }
    }

You don’t need to override all of these methods. For the sake of simplicity, we will override only the OnReceive method to build a custom actor class with minimal functionality. The following code snippet creates a custom actor class named BasicActor.

public class BasicActor : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            if (message is string)
            {
                var msg = message as string;
                Console.WriteLine(msg);
            }
        }
    }

To create an instance of an actor, you should take advantage of the Akka.Actor.ActorSystem class. An ActorSystem may be defined as a hierarchical collection of actors that have identical configuration. The following code snippet shows how you can create an instance of our BasicActor class and then pass messages to it.

static void Main(string[] args)
        {
            var actorSystem = ActorSystem.Create(“IDGActorSystem”);
            var basicActor = actorSystem.ActorOf<BasicActor>();
            basicActor.Tell(“Hello World!”);
            Console.ReadLine();
        }

It should be noted here that when you send a message to an actor, the message is delivered to a mailbox that is sorted in FIFO (first in, first out) order. The mailbox forwards the message to the OnReceive method only when the actor is available to process it.

Here is the complete code listing for your reference.

using Akka.Actor;
using System;
namespace IDGAkkaDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var actorSystem = ActorSystem.Create(“IDGActorSystem”);
            var basicActor = actorSystem.ActorOf<BasicActor>();
            basicActor.Tell(“Hello World!”);
            Console.ReadLine();
        }
    }
    public class BasicActor : UntypedActor
    {
       protected override void OnReceive(object message)
        {
            if (message is string)
            {
                var msg = message as string;
                Console.WriteLine(msg);
            }
        }
    }
}

When you run the above program, the message “Hello World!” will be displayed in the console window.

Akka.Net is a great choice when you need concurrency and distributed computation, as it allows you to work with high-level abstractions in lieu of threads and co-routines. It is resilient by design and supports adaptive load balancing, partitioning, routing, and configuration-based remoting.

I will revisit Akka.Net in future posts here. Until then, you can learn more about Akka.Net and the actor model by exploring the content available at Petabridge’s Akka.Net bootcamp.