I have a Azure Service Bus queue where I\'m receiving a range from 1 to 10 messages with the same \"key\". One of these messages needs to be processed with a long running operat
You're nearly there... do you need the incoming order preserved? If not:
public static void Main(string[] args)
{
Enumerable.Range(1, 1000)
.AsParallel()
.ForAll( i => ManageConcurrency(i % 2, () => Task.Delay(TimeSpan.FromSeconds(10))).Wait());
}
private static readonly ConcurrentDictionary _lockDict = new ConcurrentDictionary();
private static async Task ManageConcurrency(int taskId, Func task)
{
var gate = _lockDict.GetOrAdd(taskId, _ => new SemaphoreSlim(1, 1));
await gate.WaitAsync();
try
{
Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss.ffffff")}, {taskId}, Lock pulled for TaskId {taskId}, Thread Id: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
await task();
return true;
}
catch (Exception e)
{
return false;
}
finally
{
gate.Release();
}
}