Implementing the Actor-Model in C#

After learning the basics (isolated state, communication and computation) of the the Actor-Model I I wrote my own implementation and I'm ready for a through code review.

You will be able to see that in the test code I've created 2 tasks which are simultaneously sends multiple messages to an instance of the Actor class.

What I'm wondering the most is if the use of threading within the actor is correct for processing the incoming messages or should I process messages without a thread.

Full code:

using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks;  namespace ActorModel {     /// <summary>     /// Client/Test Code     /// </summary>     public static class Program     {         private static void Main()         {             var actor = new Actor<string>(x => Console.WriteLine(x.ToUpper())).Start();             var task1 = Task.Factory.StartNew(() => SendMessagesToActor(actor));             var task2 = Task.Factory.StartNew(() => SendMessagesToActor(actor));             Task.WaitAll(new[] {task1, task2});             Console.WriteLine();             Console.WriteLine();             Console.WriteLine("PRESS ENTER TO STOP THE ACTOR");             Console.ReadLine();              actor.Stop();         }          private static void SendMessagesToActor(Actor<string> actor)         {             var counter = 0;             while (counter < 5)             {                 actor.Send(String.Format("message #[{0}] from thread #[{1}]", counter,                                          Thread.CurrentThread.ManagedThreadId));                 Thread.Sleep(100); // To avoid of OutOfMemory issues                 counter++;             }         }     }      /// <summary>     /// Actor-Based Class      /// </summary>     /// <remarks>basics: Immutability, Communication and Computation</remarks>     /// <typeparam name="TMessage"></typeparam>     public class Actor<TMessage> where TMessage : class     {         private volatile bool _started;         private readonly Action<TMessage> _messageHandler;         private readonly ConcurrentQueue<TMessage> _messagesQueue; // Consider replace with TPL workflow         private readonly Task _processingTask;         private readonly CancellationTokenSource _source;          public Actor(Action<TMessage> messageHandler)         {             if (messageHandler == null)             {                 throw new ArgumentNullException("messageHandler");             }             _messagesQueue = new ConcurrentQueue<TMessage>();             _messageHandler = messageHandler;              _source = new CancellationTokenSource();             _processingTask = new Task(() => ProcessMessages(_source.Token), _source.Token, TaskCreationOptions.LongRunning);         }          //---------------------------------------------------------------------------------------------------------------------------------------------------          public Actor<TMessage> Start()         {             if (!_started)             {                 _processingTask.Start();                 _started = true;             }              return this;         }          public void Stop()         {             Console.WriteLine("PROCESSING STOP REQUESTED");             _source.Cancel();         }          //---------------------------------------------------------------------------------------------------------------------------------------------------          public void Send(TMessage message)         {             _messagesQueue.Enqueue(message); // any capacity bounding is required here?         }          //---------------------------------------------------------------------------------------------------------------------------------------------------          private void ProcessMessages(CancellationToken ct)         {             while (true)             {                 if (_messagesQueue.Count > 0)                  {                     TMessage message;                     var hasRemoved = _messagesQueue.TryDequeue(out message);                      if (hasRemoved)                     {                         _messageHandler(message);                     }                      continue;                 }                  if (ct.IsCancellationRequested)                 {                     Console.WriteLine("PROCESSING STOPED");                     return;                 }             }         }     } } 

Replay

There is one drawback(?) in your actor, in some cases it can't be interrupted.
Actor can't be stopped untill there are tasks in inner queue.
So if some outer threads will enque new tasks little bit faster then actor can process it, then you wan't be able to stop your actor.
If it's an actors feature - ok, else you can fix it by removing continue or placing cancellation check at the top of the loop.

Category: c# Time: 2016-08-02 Views: 25

Related post

  • How is the actor model used? 2011-08-08

    I have read a bit about the actor model, but don't really understand how to use actors in a real world situation – how to model a problem with them. Can someone please explain? A simple example or links to examples would be much appreciated. --------

  • Is my description of the actor model right? 2011-10-28

    If I understood, the actor model is just like the object model, but with a few differences: EVERY object spawns it's own separate thread and its not a problem even when you have thousands of objects. Actors don't interact by calling functions and get

  • Scale parameter error when implementing the pmf model with pystan 2016-02-13

    I am trying to implement the pmf model. And my code is as below: pmf_code = """ data { int<lower=0> K; //number of factors int<lower=0> N; //number of user int<lower=0> M; //number of item int<lower=0> D; //number of

  • What are the recommended resources for learning about the Actor model of concurrent systems? 2011-11-03

    The Actor concurrency model is clearly gaining favor. Is there a good book that presents the patterns and pitfalls of the model? I am thinking about something that would discuss, for instance, the problems of consistency and correctness in the contex

  • Unable to implement the FIR model in Matlab 2016-07-14

    I want to generate a wireless fading channel that is modeled as Moving Average process with Rayleigh fading coefficients. The numver of multipath is M =3 and the power delay profile is fixed as 0,-3, and -6 dB. The channel coefficients are modeled ac

  • Using an actor model versus a producer-consumer model? 2011-06-04

    I'm doing some early-stage research towards architecting a new software application. Concurrency and multithreading will likely play a significant part, so I've been reading up on the various topics. The producer-consumer model, at least how it is ex

  • Why is Akka being marketed as reactive? Is Actor Model reactive? 2014-09-01

    As far as I understand the Actor Model and the Reactive Programming are separate concepts. Actor Model does not seem to be inherently reactive to me. However the Akka framework which is an Actor Model implementation is being described as reactive: "J

  • Is Erlang really an actor model language? 2015-03-26

    I was reading this article: http://www.doc.ic.ac.uk/~nd/surprise_97/journal/vol2/pjm2/ And it mentions that: ...in the actor model even an integer is represented as an actor... Wikipedia confirms: The Actor model adopts the philosophy that everything

  • Multi thread approach vs Akka actor model 2016-01-21

    I'm new to akka actor. I have read the akka offical documents and still don't understand how actor works compare to threading model. Let's take a simple example like this. I have a traditional HttpServer , which have 10 threads in the thread pools .

  • Polyglot Node.js with Typesafe Akka for Actor Model 2015-07-03

    I have a case that needs to manipulate a large stream of JSON and inject it into Apache HBase. Our system works on Node.js with Mongo then, since we need to enhance performance, so HBase is choosen to handle the big data things. To enhance my system

  • Open-source GIS implementation of the Huff model 2011-02-16

    This might be a stretch, but I was wondering if anyone implemented gravity modeling tools or scripts for Retail Market Analysis (like the Huff Model), to analyze spatial data for customer-store relationships? There are a couple ESRI sources (includin

  • How should I implement the repository pattern for complex object models? 2012-10-16

    Our data model has almost 200 classes that can be separated out into about a dozen functional areas. It would have been nice to use domains, but the separation isn't that clean and we can't change it. We're redesigning our DAL to use Entity Framework

  • How can I implement A* so that it accounts for the size of the actor? 2016-02-02

    I'm trying to make a little A* implementation using polygon verticies as nodes instead of grids and I ran into the problem of figuring out what paths are wide enough to accommodate the actor moving through them. Lets say the actor was 10x10 and the s

  • Using different shaders on the same model at runtime 2013-07-04

    I've already asked similar but a bit unclear question here but this time I will be very specific and to the point. Suppose I have an actor which grabs a power up. He starts to glow using bloom shader and after 10 seconds back to normal attaching the

  • Who know how to implement the 2D bone animation showed in the game? 2010-12-28

    I wonder how do they implement the bone animation in the flash game http://www.foddy.net/athletics.swf Do you know any study materials which I can start to learn 2D bone system from? I just implemented a avatar system by compose multiple bitmaps in e

  • Small projects using the cathedral model: does open-source lower security? 2011-02-25

    We know of Linus' law: With enough eyeballs all bugs are shallow In general, people seem to say that open-source software is more secure because of that very thing, but... There are many small OSS projects with just 1 or 2 developers (the cathedral m

  • Possible to find EVERYTHING that references a list using PowerShell or the Object Model? 2011-05-27

    I recently did a migration from SharePoint 2007 to 2010. In the end I had to re-implement a number of things (such as workflows) because they referenced lists, and the list GUIDs changed during the migration. I looked into creating a list with a spec

  • Using MVP, how to create a view from another view, linked with the same model object 2011-06-24

    Background We use the Model-View-Presenter design pattern along with the abstract factory pattern and the "signal/slot" pattern in our application, to fullfill 2 main requirements Enhance testability (very lightweight GUI, every action can be si

  • Should the domain model include all the domain entities in my project? 2011-08-30

    I have currently reading Grails and I love it. In order to get hands on experience with Grails I decided to create a web application for some Management System. Ya as you can guess there are plenty of entities that goes into the domain model for my w

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 1.365 (s). 13 q(s)