question

JAL-9381 avatar image
0 Votes"
JAL-9381 asked JAL-9381 commented

How to lock a method accessed by both classic threads and async threads

I thought I heard somewhere that the lock-keyword isn't reliable on asynchronous threads. The complication here is that I have both classic threads and asynchronous threads trying to access my method. What kind of lock will work for both types of threads?

lock(oLocker) {
//code here.
}


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered JAL-9381 commented

The use of async-await and lock together is indeed prone to problems.

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.

C# Lock and Async Method

SemaphoreSlim Class may be useful to you.


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I think I'm making this too complicated. The protected code (the code within my lock-block) is only doing synchronous operations. In fact the lock-block itself is within a synchronous method. Therefore the traditional lock-keyword should work fine, right?

0 Votes 0 ·

I think so, in the synchronization code, there should be no problem using lock.
lock statement (C# reference)

1 Vote 1 ·