C# Lock and Async Method

后端 未结 4 1823
星月不相逢
星月不相逢 2021-02-05 03:22

I am not clear (and can\'t find documentation clear enough): when using the lock keyword in an async method: will the thread be blocked if the object is already blocked or will

相关标签:
4条回答
  • 2021-02-05 03:37

    No it won't.

    lock is syntactic sugar for Monitor.Enter and Monitor.Exit. lock will keep execution in the method until the lock is released. It does not function like await in any way, shape or form.

    0 讨论(0)
  • 2021-02-05 03:46

    You task will not return in suspended state. It will wait until myLock is unlocked to run the code within lock statement. It will happen no matter what C# asynchronous model you use.

    In other words, no two threads will be able to run statements inside the lock. Unless, there are many different instances of myLock object.

    0 讨论(0)
  • 2021-02-05 03:56

    This has been disallowed to stop deadlocks (i.e. developers hurting themselves). The best solution I've found is to use semaphores - See this post for details.

    Relevant code extract:

    static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
    
    ...
    
    await semaphoreSlim.WaitAsync();
    try
    {
        await Task.Delay(1000);
    }
    finally
    {
        semaphoreSlim.Release();
    }
    
    0 讨论(0)
  • 2021-02-05 04:04

    In the code below, will the line block the thread?

    Technically, yes, but it won't work as you expect.

    There are two reasons why thread-affine locks don't play well with async. One is that (in the general case), an async method may not resume on the same thread, so it would try to release a lock it doesn't own while the other thread holds the lock forever. The other reason is that during an await while holding a lock, arbitrary code may execute while the lock is held.

    For this reason, the compiler goes out of its way to disallow await expressions within lock blocks. You can still shoot yourself in the foot by using Monitor or other primitives directly, though.

    If it blocks the thread (which is what I think), is there an standard not blocking solution?

    Yes; the SemaphoreSlim type supports WaitAsync.

    0 讨论(0)
提交回复
热议问题