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

  • Mastering Blazor Authentication and Authorization

    At the Visual Studio Live! @ Microsoft HQ developer conference set for August, Rockford Lhotka will explain the ins and outs of authentication across Blazor Server, WebAssembly, and .NET MAUI Hybrid apps, and show how to use identity and claims to customize application behavior through fine-grained authorization.

  • Linear Support Vector Regression from Scratch Using C# with Evolutionary Training

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the linear support vector regression (linear SVR) technique, where the goal is to predict a single numeric value. A linear SVR model uses an unusual error/loss function and cannot be trained using standard simple techniques, and so evolutionary optimization training is used.

  • Low-Code Report Says AI Will Enhance, Not Replace DIY Dev Tools

    Along with replacing software developers and possibly killing humanity, advanced AI is seen by many as a death knell for the do-it-yourself, low-code/no-code tooling industry, but a new report belies that notion.

  • Vibe Coding with Latest Visual Studio Preview

    Microsoft's latest Visual Studio preview facilitates "vibe coding," where developers mainly use GitHub Copilot AI to do all the programming in accordance with spoken or typed instructions.

  • Steve Sanderson Previews AI App Dev: Small Models, Agents and a Blazor Voice Assistant

    Blazor creator Steve Sanderson presented a keynote at the recent NDC London 2025 conference where he previewed the future of .NET application development with smaller AI models and autonomous agents, along with showcasing a new Blazor voice assistant project demonstrating cutting-edge functionality.

Subscribe on YouTube