Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active February 3, 2016 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogeralsing/6ea258a552b3f3c2fc27 to your computer and use it in GitHub Desktop.
Save rogeralsing/6ea258a552b3f3c2fc27 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Dispatch.SysMsg;
namespace ConsoleApplication43
{
class Program
{
static void Main(string[] args)
{
using (var system = ActorSystem.Create("sys"))
{
var parent = system.ActorOf<Parent>();
parent.Tell("work");
parent.Tell("work");
parent.Tell("terminate");
//these will never be processed
parent.Tell("work");
parent.Tell("work");
parent.Tell("work");
Console.ReadLine();
}
}
}
public class Parent : ReceiveActor
{
private readonly HashSet<IActorRef> _children = new HashSet<IActorRef>();
public Parent()
{
for (int i = 0; i < 10; i++)
{
var child = Context.ActorOf<Worker>();
Context.Watch(child);
_children.Add(child);
}
Receive<string>(str => str == "work", s =>
{
foreach (var child in _children)
{
//send some sort of work to child
child.Tell("work" + Guid.NewGuid());
}
});
Receive<string>(str => str == "terminate", s =>
{
BecomeTerminating();
});
}
private void BecomeTerminating()
{
foreach (var child in _children)
{
child.Tell(PoisonPill.Instance);
}
Become(Terminating);
}
private void Terminating()
{
Receive<Terminated>(t =>
{
_children.Remove(t.ActorRef);
if (!_children.Any())
{
//all children are dead
Context.Stop(Self);
}
});
}
protected override void PostStop()
{
Console.WriteLine("Stopping parent");
base.PostStop();
}
}
public class Worker : ReceiveActor
{
public Worker()
{
Receive<string>(s => Console.WriteLine($"Doing work {Self.Path}"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment