Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't suggest inside lock #32

Open
Jesse-Hufstetler opened this issue Apr 20, 2018 · 1 comment
Open

Don't suggest inside lock #32

Jesse-Hufstetler opened this issue Apr 20, 2018 · 1 comment

Comments

@Jesse-Hufstetler
Copy link

You can't do async in a lock
image
Stop squigglin' me!

@avonwyss
Copy link

avonwyss commented Aug 2, 2018

The reason why it isn't allowed is explained well here:
https://stackoverflow.com/questions/7612602/why-cant-i-use-the-await-operator-within-the-body-of-a-lock-statement/7612714#7612714
In summary, since locks are inherently thread-bound but async code is not, awaiting in a lock is a receipe for deadlocking.

However, by using other locking mechanisms such as SemaphoreSlim it is possible to implement rougly equivalent functionality from the locking point of view while keeping things async.

Therefore, the AsyncConverter could maybe provide a way to convert lock(X) (where X must be a object field/property only used for locking) to have X be a SemaphoreSlim(1, 1) instance and replace all usages of the lock(X) {...} with something like this:

await X.WaitAsync();
try {
  ...
} finally {
  X.Release();
}

(Note: non-async code doing lock(X) would need to do X.Wait() instead of await X.WaitAsync();)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants