Skip to content

Commit 0879b08

Browse files
committed
Handle abandoned mutex exception
1 parent cc6eaa7 commit 0879b08

File tree

1 file changed

+27
-16
lines changed

1 file changed

+27
-16
lines changed

PSReadLine/History.cs

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -127,27 +127,38 @@ private void ReportHistoryFileError(Exception e)
127127

128128
private bool WithHistoryFileMutexDo(int timeout, Action action)
129129
{
130-
if (_historyFileMutex.WaitOne(timeout))
130+
int retryCount = 0;
131+
do
131132
{
132133
try
133134
{
134-
action();
135-
}
136-
catch (UnauthorizedAccessException uae)
137-
{
138-
ReportHistoryFileError(uae);
139-
return false;
140-
}
141-
catch (IOException ioe)
142-
{
143-
ReportHistoryFileError(ioe);
144-
return false;
135+
if (_historyFileMutex.WaitOne(timeout))
136+
{
137+
try
138+
{
139+
action();
140+
}
141+
catch (UnauthorizedAccessException uae)
142+
{
143+
ReportHistoryFileError(uae);
144+
return false;
145+
}
146+
catch (IOException ioe)
147+
{
148+
ReportHistoryFileError(ioe);
149+
return false;
150+
}
151+
finally
152+
{
153+
_historyFileMutex.ReleaseMutex();
154+
}
155+
}
145156
}
146-
finally
157+
catch (AbandonedMutexException)
147158
{
148-
_historyFileMutex.ReleaseMutex();
159+
retryCount += 1;
149160
}
150-
}
161+
} while (retryCount > 0 && retryCount < 3);
151162

152163
// No errors to report, so consider it a success even if we timed out on the mutex.
153164
return true;
@@ -196,7 +207,7 @@ private bool MaybeReadHistoryFile()
196207
return WithHistoryFileMutexDo(1000, () =>
197208
{
198209
var fileInfo = new FileInfo(Options.HistorySavePath);
199-
if (fileInfo.Length != _historyFileLastSavedSize)
210+
if (fileInfo.Exists && fileInfo.Length != _historyFileLastSavedSize)
200211
{
201212
var historyLines = new List<string>();
202213
using (var fs = new FileStream(Options.HistorySavePath, FileMode.Open))

0 commit comments

Comments
 (0)