joydip_kanjilal
Contributor

How to get started with Akka.Net

how-to
Aug 28, 20175 mins
Small and Medium BusinessSoftware Development

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

command line
Credit: 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.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author