Last active
February 3, 2016 13:14
-
-
Save rogeralsing/6ea258a552b3f3c2fc27 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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