In my previous article about the Actor Model, I introduced the Proto.Actor framework. Today, I’ll walk through a simple "Hello World" example to demonstrate its core concepts.
Why Proto.Actor?
Proto.Actor was created by the developer behind the initial port of Akka (from Java to .NET). Building on lessons learned during that project, the team prioritized leveraging existing technologies over reinventing the wheel. For example, Proto.Actor uses gRPC for serialization instead of maintaining a custom solution like Akka.NET. This focus on simplicity and interoperability makes it a compelling choice for actor-based systems.
Another standout feature is Proto.Actor’s excellent documentation, which provides deep insights into both the Actor Model and practical framework usage.
Prerequisites
- .NET 6+ SDK installed
- Basic familiarity with C#
Step 1: Create a Project
- Create a new console project:
dotnet new console -n ProtoActorDemo
- Add the Proto.Actor package:
dotnet add package Proto.Actor
Step 2: Define Messages
Actors communicate via messages. In C#, record types are ideal due it immutability
public record Hello(string Who);
Why immutability? Immutable messages prevent side effects and ensure thread safety—a core tenet of the Actor Model.
Step 3: Implement an Actor
Actors process messages asynchronously. Create a GreetingActor by implementing IActor:
public class GreetingActor : IActor
{
public Task ReceiveAsync(IContext context)
{
if (context.Message is Hello hello)
{
Console.WriteLine($"Hello {hello.Who}!");
}
return Task.CompletedTask;
}
}
Step 4: Start the Actor System
Initialize the system, spawn the actor, and send messages:
var system = new ActorSystem();
var props = Props.FromProducer(() => new GreetingActor());
var greeter = system.Root.Spawn(props);
while (true)
{
Console.Write("Enter your name (q to quit): ");
var name = Console.ReadLine();
if (string.IsNullOrEmpty(name))
{
continue;
}
if (name == "q")
{
break;
}
system.Root.Send(greeter, new Hello(name));
await Task.Delay(TimeSpan.FromSeconds(1)); // Give some time to Actor system process the message
}
Conclusion
In under 20 lines of code, we’ve built a functional actor system! Proto.Actor’s simplicity and documentation make it easy to get started.
Next up: We’ll explore virtual actors (a.k.a. "grains").
Top comments (0)