Skip to content

Instantly share code, notes, and snippets.

@jvandertil
Last active December 11, 2015 05:08
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 jvandertil/4550276 to your computer and use it in GitHub Desktop.
Save jvandertil/4550276 to your computer and use it in GitHub Desktop.
Shows optimistic concurrency at work for the Azure Tables implementation of JOliver's EventStore
using System;
using EventStore;
namespace EventStoreConcurrencyTest
{
class Program
{
static void Main(string[] args)
{
var eventStore1 = WireupEventStore();
var eventStore2 = WireupEventStore();
ConcurrencyException caughtException = null;
Guid aggregateId = Guid.NewGuid();
// A single commit to start with.
using (var stream = eventStore1.CreateStream(aggregateId))
{
stream.Add(new EventMessage() { Body = new object() });
stream.CommitChanges(Guid.NewGuid());
}
var stream1 = eventStore1.OpenStream(aggregateId, 0, int.MaxValue);
var stream2 = eventStore2.OpenStream(aggregateId, 0, int.MaxValue);
// Stream 1 commits first.
stream1.Add(new EventMessage() { Body = new object() });
stream1.CommitChanges(Guid.NewGuid());
stream1.Dispose();
// Stream 2 is writing 'concurrently'
stream2.Add(new EventMessage() { Body = new object() });
try
{
stream2.CommitChanges(Guid.NewGuid());
}
catch (ConcurrencyException ce)
{
// Result of a HTTP 409 Conflict response
caughtException = ce;
}
if (caughtException != null)
{
Console.WriteLine("Caught ConcurrencyException. Optimistic Concurrency is working.");
}
else
{
// Does not happen :).
Console.WriteLine("Did not catch an exception :(. Concurrency detection does not work.");
}
stream2.Dispose();
eventStore1.Dispose();
eventStore2.Dispose();
}
private static IStoreEvents WireupEventStore()
{
var es = Wireup.Init()
.LogToOutputWindow()
.UsingAzureTablesPersistence("Tables")
.InitializeStorageEngine()
.UsingBinarySerialization()
.Build();
return es;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment