A minimal actor framework
Join the DZone community and get the full member experience.
Join For Freefor one of our projects, we need the ability to asynchronously push changes through a socket, since we actually care about the order of actions, we realized that we couldn’t really use purely async io. for example, consider the following actions:
connection.send(“abc”); connection.send(“def”);
i care that abc will be sent before def, and i care that all of abc will be sent before anything else is sent through that connection. what i don’t care about is whatever i have anything else sent between abc and def.
all of that can be had using:
public class actor<tstate> { public tstate state { get; set; } private readonly concurrentqueue<action<tstate>> actions = new concurrentqueue<action<tstate>>(); private task activetask; public void act(action<tstate> action) { actions.enqueue(action); if (activetask != null) return; lock(this) { if (activetask != null) return; activetask = task.factory.startnew(executeactions); } } private void executeactions() { action<tstate> action; while (actions.trydequeue(out action)) { action(state); } lock(this) { activetask = null; } } }
the actions will execute synchronously for each actor, and it satisfy
my requirement for how to deal with this quite nicely, even if i say so
myself
in truth, the code above isn’t really good. can you consider ways to improve this?
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments