Practical ASP.NET

Modelling Actor Behaviors in Akka.NET

Simplify conditional actor code and improve readability.

When using Akka.NET to build concurrent systems, the actor code that you write can become complicated if there are many different ways an actor can respond to a message. One of the features of actors in the Actor Model is that they can change their behavior over time. This switching of behavior can make it easier to represent what your actors should do.

An Example Without Switchable Behaviour
As an example, suppose you have an actor that represents the eye (a camera) of a robot. This eye has a robotic eyelid that can be opened or closed. This actor can respond to three types of messages:

  • OpenEyeMessage
  • CloseEyeMessage
  • TakePhotoMessage

Table 1 shows the way these different messages need to be handled depending on the current state of the eye.

Table 1: Processing Messages Depending on Current State
Message Eye Open Eye Closed
OpenEyeMessage Do nothing Open robotic eye
CloseEyeMessage Close robotic eye Do nothing
TakePhotoMessage Take a photo Error, eye is closed

You could implement the behavior of your actor by holding the current state of the eye in a Boolean _eyeIsOpen field in the actor and then having conditional if statements based on this field as shown in Listing 1.

Listing 1: Implement Different Behavior Manually
class RobotEyeActor : ReceiveActor
{
  private bool _eyeIsOpen; // Default to closed

  public RobotEyeActor()
  {
    Receive<OpenEyeMessage>(
      message =>
      {
        if (_eyeIsOpen)
        {
          // Do nothing
        }
      else
      {
        // Open robotic eye
        eyeIsOpen = true;
      }
      });


    Receive<CloseEyeMessage>(
      message =>
      {
        if (_eyeIsOpen)
        {
          // Close robotic eye
          _eyeIsOpen = false;
        }
        else
        {
          // Do nothing
        }
      });


    Receive<TakePhotoMessage>(
      message =>
      {
        if (_eyeIsOpen)
        {
          // Take photo
        }
        else
        {
          // Error, eye is not open
          }
      });
  }
}

Using Switchable Actor Behaviours
Akka.NET actors have access to the Become method that allows their behavior to be changed at runtime. Doing this you can control how the next message will be processed -- the message being currently processed will be unaffected. Listing 2 shows the use of the Become method to represent the eye open and eye closed behaviors. Notice that you don't need the Boolean field when taking this approach.

Listing 2: Using the Become Method To Represent the Eye Open and Eye Closed Behaviors
class RobotEyeActor : ReceiveActor
{
  public RobotEyeActor()
  {
    Closed();
  }

  private void Closed()
  {
    Receive<OpenEyeMessage>(
      message =>
      {
        // Open robotic eye

        Become(Open);
      });


    Receive<CloseEyeMessage>(
      message =>
      {
        // Do nothing
      });


    Receive<TakePhotoMessage>(
      message =>
      {
        // Error, eye is not open
      });
  }

  private void Open()
  {
    Receive<OpenEyeMessage>(
      message =>
      {
        // Do nothing
      });


    Receive<CloseEyeMessage>(
      message =>
      {
        // close robotic eye

        Become(Closed);
      });


    Receive<TakePhotoMessage>(
      message =>
      {
        // take photo
      });
  }
}

Notice here that you set the initial behavior of the actor when it's created to Closed in the constructor. Here you don't need to use the Become method because you're setting the initial state. In response to incoming messages, you can change the behavior of the actor over time in response to messages that it receives.

Switchable behaviors are a powerful technique, which once mastered, can make actor code easier to reason about and code. In the examples in this article you only have two states (opened and closed). Imagine if you had six message types and four distinct states -- writing this code with if statements could quickly become unmanageable.

About the Author

Jason Roberts is a Microsoft C# MVP with over 15 years experience. He writes a blog at http://dontcodetired.com, has produced numerous Pluralsight courses, and can be found on Twitter as @robertsjason.

comments powered by Disqus

Featured

  • Full Stack Hands-On Development with .NET

    In the fast-paced realm of modern software development, proficiency across a full stack of technologies is not just beneficial, it's essential. Microsoft has an entire stack of open source development components in its .NET platform (formerly known as .NET Core) that can be used to build an end-to-end set of applications.

  • .NET-Centric Uno Platform Debuts 'Single Project' for 9 Targets

    "We've reduced the complexity of project files and eliminated the need for explicit NuGet package references, separate project libraries, or 'shared' projects."

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

Subscribe on YouTube