Skip to content

Instantly share code, notes, and snippets.

@andrevdm
Last active September 28, 2015 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrevdm/1393117 to your computer and use it in GitHub Desktop.
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
//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