Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • 298
    How do you handle a scenario where you need to return a cache entry, and if the entry does not exist you need to compute asynchronously the content then add+return the entry, making sure nobody else calls you in the meantime ? Commented Aug 25, 2012 at 5:32
  • 18
    I realise I'm late to the party here, however I was surprised to see that you put deadlocks as the primary reason why this is a bad idea. I had come to the conclusion in my own thinking that the re-entrant nature of lock/Monitor would be a bigger part of the problem. That is, you queue two tasks to the thread pool which lock(), that in a synchronous world would execute on separate threads. But now with await (if allowed I mean) you could have two tasks executing within the lock block because the thread was reused. Hilarity ensues. Or did I misunderstand something? Commented Dec 12, 2012 at 22:56
  • 5
    @GarethWilson: I talked about deadlocks because the question asked was about deadlocks. You are correct that bizarre re-entrancy issues are possible and seem likely. Commented Dec 12, 2012 at 23:10
  • 17
    @Eric Lippert. Given that the SemaphoreSlim.WaitAsync class was added to the .NET framework well after you posted this answer, I think we can safely assume that it is possible now. Regardless of this, your comments about the difficulty of implementing such a construct are still entirely valid. Commented Sep 12, 2014 at 8:34
  • 16
    "arbitrary code runs between the time the await returns control to the caller and the method resumes" - surely this is true of any code, even in the absence of async/await, in a multithreaded context: other threads may execute arbitrary code at any time, and said arbitrary code as you say "could be taking out locks that produce lock ordering inversions, and therefore deadlocks." So why is this of particular significance with async/await? I understand the second point re "the code could resume on another thread" of being of particular significance to async/await. Commented Sep 28, 2016 at 22:12