Last active
September 28, 2015 05:38
-
-
Save andrevdm/1393117 to your computer and use it in GitHub Desktop.
Simple C# clojure like agent. Supports async/await and returning values from the wrapped data structure
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
//Serialised, asynchronous access to data structures | |
public class Agent<T> | |
{ | |
private readonly T m_data; | |
private readonly BlockingCollection<Action<T>> m_actions = new BlockingCollection<Action<T>>( new ConcurrentQueue<Action<T>>() ); | |
public Agent( T data ) | |
{ | |
if( data == null ) | |
{ | |
throw new ArgumentNullException( "data" ); | |
} | |
m_data = data; | |
Task.Factory.StartNew( ProcessActions ); | |
} | |
public void Send( Action<T> act ) | |
{ | |
if( act != null ) | |
{ | |
m_actions.Add( act ); | |
} | |
} | |
private void ProcessActions() | |
{ | |
foreach( var action in m_actions.GetConsumingEnumerable() ) | |
{ | |
action( m_data ); | |
} | |
} | |
} | |
//Usage e.g. | |
var agent = new Agent<List<string>>( new List<string>() ); | |
agent.Act( lst => lst.Add( "1" ) ); | |
agent.Act( lst => lst.Add( "2" ) ); | |
agent.Act( lst => lst.ForEach( Console.WriteLine ) ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment