-
-
Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Minimalist C# Actors
This file contains 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
// Inspired by https://gist.github.com/2557678 | |
// and http://dspace.mit.edu/bitstream/handle/1721.1/6935/AITR-633.pdf | |
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Threading.Tasks.Dataflow; | |
using Message = System.Object; | |
namespace Actors | |
{ | |
public interface Behavior { Behavior OnArrival(Message message); } | |
public class Actor | |
{ | |
private volatile Behavior behavior; | |
private readonly ActionBlock<Message> arrivals; | |
public Actor(Behavior initialBehavior) | |
{ | |
this.behavior = initialBehavior; | |
this.arrivals = new ActionBlock<Message>(message => { this.behavior = this.behavior.OnArrival(message); }); | |
} | |
public void Send(Message message) | |
{ | |
this.arrivals.SendAsync(message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You'll have to unsafely publish the reference to the newly allocated Actor and have the thread that picks it up send it a message.