Skip to content

Instantly share code, notes, and snippets.

@JohnNilsson
Forked from viktorklang/Actor.java
Created May 6, 2012 22:17
Show Gist options
  • Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Save JohnNilsson/2624807 to your computer and use it in GitHub Desktop.
Minimalist C# Actors
// 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);
}
}
}
@viktorklang
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment