3

i need to lock a method preventing multiple simultaneous execution, this is my solutions, is it thread safe? is it safe?

    public async Task ExecuteApiCalls()
    {
        lock (lockObject)
        {
             var t = Task.Run(async () => {
                //my async code  
             }  
             Task.WaitAny(t);
        });

        
        
    }
Fildor
  • 14,510
  • 4
  • 35
  • 67
danilonet
  • 1,757
  • 16
  • 33
  • 3
    *Waiting for Stephen C to chime in ... – Fildor Oct 08 '20 at 15:48
  • 4
    I think you should consider [SemaphoreSlim](https://learn.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netcore-3.1). – Fildor Oct 08 '20 at 15:48
  • 2
    This may be interesting, too (read Eric Lippert's answer). https://stackoverflow.com/q/7612602/982149 – Fildor Oct 08 '20 at 15:53
  • Why don't you lock in the very inner function? – Wiktor Zychla Oct 08 '20 at 15:56
  • 1
    Also: [Async/Await - Best Practices in Asynchronous Programming - Know Your Tools](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#know-your-tools) : _"Problem: Synchronize access to a shared resource , Solution: SemaphoreSlim"_ – Fildor Oct 08 '20 at 16:06

0 Answers0