Release mutex when facing AbandonedMutexException #2867
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Summary
Fix #2742
When getting a
AbandonedMutexException
, the current thread actually owns the mutex at that point, and thus it must release it. Otherwise, the mutex object will be kept held by that thread, resulting in allWaitOne
calls from other PowerShell processes always time out.Quoted from the sample code for
AbandonedMutexException
I have verified that when not releasing mutex in case of
AbandonedMutexException
, another thread callingWaitOne
on the mutex will always time out (see the output messages below).In the sample program, the mutex is not released in the exception handler when
AbandonedMutexException
is caught in the main thread. The subsequent retry of theWaitOne
call in main thread succeeded, but even thoughReleaseMutex
is called for that successfulWaitOne
call, the main thread is still holding the mutex, because it didn't release the mutex whenAbandonedMutexException
was caught.Then when trying to call
WaitOne
on the same mutex object from a different thread, the call always times out.So the fix in PSReadLine is to call
ReleaseMutex()
in the exception handler ofAbandonedMutexException
, so that we don't miss a release and indefinitely hold the mutex without knowing. TBH, I don't know how the mutex could be abandoned by PSReadLine. It seems impossible by looking at the code, but I guess it could happen for some random reasons. It would be nice to have diagnostics telemetry in PSReadLine to help confirm that.PR Checklist
Microsoft Reviewers: Open in CodeFlow