Search Results for

    Show / Hide Table of Contents

    Console Application

    Create Message Class Greet

    The way to tell an actor to do something is by sending it a message. Greet is the message type to be sent!

    namespace HelloWorld
    {
        /// <summary>
        /// Immutable message type that actor will respond to
        /// </summary>
        public class Greet
        {
            public string Who { get; private set; }
    
            public Greet(string who)
            {
                Who = who;
            }
        }
    }
    

    Creating the GreetingActor

    using Akka.Actor;
    
    namespace HelloWorld
    {
        /// <summary>
        /// The actor class
        /// </summary>
        public class GreetingActor : ReceiveActor
        {
            public GreetingActor()
            {
                // Tell the actor to respond to the Greet message
                Receive<Greet>(greet => Console.WriteLine($"Hello {greet.Who}"));
            }
            protected override void PreStart()
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Good Morning, we are awake!");
            }
    
            protected override void PostStop()
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Good Night, going to bed!");
            }
        }
    }
    

    PreStart will be called by the Akka framework when the actor is getting started. The PostStop will be called after the actor is stopped.

    Creating a Console Host

    ActorSystem system = ActorSystem.Create("the-universe");
    
    // create actor and get a reference to it.
    // this will be an "ActorRef", which is not a 
    // reference to the actual actor instance
    // but rather a client or proxy to it
    IActorRef greeter = system.ActorOf<GreetingActor>("greeter");
    
    // send a message to the actor
    greeter.Tell(new Greet("World"));
    
    // give the actor a moment to process the message
    // (it should process it in under a micro-second, but it happens asynchronously)
    await Task.Delay(TimeSpan.FromSeconds(1));
    system.Stop(greeter);
    
    await system.Terminate();
    
    In this article
    • githubEdit this page
    Back to top
    Contribute
    • Project Chat
    • Discussion Forum
    • Source Code
    Support
    • Akka.NET Support Plans
    • Akka.NET Observability Tools
    • Akka.NET Training & Consulting
    Maintained By
    • Petabridge - The Akka.NET Company
    • Learn Akka.NET