Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created May 17, 2018 13:30
Show Gist options
  • Select an option

  • Save ramonsmits/491055d070d68d1bfb2e30537bcffce5 to your computer and use it in GitHub Desktop.

Select an option

Save ramonsmits/491055d070d68d1bfb2e30537bcffce5 to your computer and use it in GitHub Desktop.
NServiceBus serialized handler
using System;
using System.Threading;
using System.Threading.Tasks;
using NServiceBus;
class SerializedHandler : IHandleMessages<MyMessage>
{
static readonly SemaphoreSlim sequentialAccess = new SemaphoreSlim(1);
static readonly TimeSpan waitDuration = TimeSpan.FromSeconds(5);
public async Task Handle(OrderReceived message, IMessageHandlerContext context)
{
try
{
var success = await sequentialAccess.WaitAsync(waitDuration)
.ConfigureAwait(false);
if (!success) throw new InvalidOperationException($"Could not acquire access within {waitDuration}");
// Do my stuff here
}
finally
{
sequentialAccess.Release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment