Keyed Lock in .Net

后端 未结 3 2014
长发绾君心
长发绾君心 2021-01-21 20:02

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

3条回答
  •  执笔经年
    2021-01-21 20:34

    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();
        }
    
    }
    

提交回复
热议问题