// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Akka.Actor; namespace SerializedAccess { public class TemperatureLogger : ReceiveActor { public enum Command { GetMax, Stop } public class Update { public int Measurement { get; set; } } private List measurements; private int max; public TemperatureLogger(int measurement) { measurements = new List(); measurements.Add(measurement); max = measurement; Receive((Command cmd) => { switch (cmd) { case Command.GetMax: Sender.Tell(max); break; case Command.Stop: Self.GracefulStop(TimeSpan.FromMilliseconds(100)); break; } }); Receive((Update updmsg) => { measurements.Add(updmsg.Measurement); if (updmsg.Measurement > max) { max = updmsg.Measurement; } }); } } public class Test : ReceiveActor { public enum Command { Action } private const int N = 100; public Test() { Receive((Command cmd) => { switch (cmd) { case Command.Action: IActorRef tl = Context.ActorOf(Props.Create(typeof(TemperatureLogger), 0)); int[] v = new int[N]; for (int i = 0; i < N; i++) { v[i] = N / 2 - Math.Abs(N / 2 - i); } Task[] t = new Task[N]; for (int i = 0; i < N; i++) { int tempv = v[i]; t[i] = Task.Factory.StartNew(() => tl.Tell(new TemperatureLogger.Update { Measurement = tempv })); } Task.WaitAll(t); Task fut = tl.Ask(TemperatureLogger.Command.GetMax, TimeSpan.FromMilliseconds(100)); int res = fut.Result; if (res != N / 2) Console.WriteLine("Ooops - wrong result: {0}", res); tl.Tell(TemperatureLogger.Command.Stop); Self.GracefulStop(TimeSpan.FromMilliseconds(100)); break; } }); } } public class Program { private const int REP = 1000; public static void Main(string[] args) { DateTime dt1 = DateTime.Now; for (int j = 0; j < REP; j++) { ActorSystem akka = ActorSystem.Create("TemperatureLogger"); IActorRef test = akka.ActorOf(Props.Create(typeof(Test))); test.Tell(Test.Command.Action); akka.Terminate(); } DateTime dt2 = DateTime.Now; Console.WriteLine("Time: {0} s", (dt2 - dt1).TotalSeconds); } } }