1

Can I use this approach safely (without risk of deadlock):

public class Foo
{
  private readonly object locker = new();

  public void Test() 
  {
     lock(locker) 
     {
        Task.Delay(TimeSpan.FromSeconds(1)).GetAwaiter().GetResult();
     }
  }
}

Or should we use something like Nito.AsyncEx:

public class Bar
{
  private readonly AsyncLock mutex = new();

  public async Task Test() 
  {
     using (await mutex.LockAsync())
     {
        await Task.Delay(TimeSpan.FromSeconds(1));
     }
  }
}
RQDQ
  • 15,461
  • 2
  • 32
  • 59
  • 1
    TLDR no it isn't safe in ASP.NET Classic, WinForms and WPF applications, among others. Console apps are OK, but would still avoid if you can. You can use a `SemaphoreSlim` for an async lock if you want to avoid a dependency – Charlieface May 23 '23 at 20:03

0 Answers0