Skip to content

Commit

Permalink
Use ReaderWriterLockSlim
Browse files Browse the repository at this point in the history
  • Loading branch information
v-wuzhai committed Sep 18, 2024
1 parent 1271b8e commit 1f2f4f4
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions src/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ public FileSystemDirectory(string name, string fullPath)

private class FileSystemFile
{
private readonly object _sync = new();
private readonly ReaderWriterLockSlim _lock = new();
private byte[] _data;
private int _currentReaders;
private int _currentWriters;
Expand All @@ -798,15 +798,31 @@ public Stream OpenRead()
throw new IOException("File is currently locked for writing");
}

lock (_sync)
_lock.EnterReadLock();
try
{
if (_currentWriters > 0)
{
throw new IOException("File is currently locked for writing");
}

++_currentReaders;
return new DisposingStream(new MemoryStream(_data, false), () => { lock (_sync) { --_currentReaders; } });
return new DisposingStream(new MemoryStream(_data, false), () =>
{
_lock.EnterWriteLock();
try
{
--_currentReaders;
}
finally
{
_lock.ExitWriteLock();
}
});
}
finally
{
_lock.ExitReadLock();
}
}

Expand All @@ -822,7 +838,8 @@ public Stream OpenWrite()
throw new IOException("File is currently locked for writing");
}

lock (_sync)
_lock.EnterWriteLock();
try
{
if (_currentReaders > 0)
{
Expand All @@ -838,16 +855,25 @@ public Stream OpenWrite()
MemoryStream target = new();
return new DisposingStream(target, () =>
{
lock (_sync)
_lock.EnterWriteLock();
try
{
--_currentWriters;
_data = new byte[target.Length];
target.Position = 0;
_ = target.Read(_data, 0, _data.Length);
LastWriteTimeUtc = DateTime.UtcNow;
}
finally
{
_lock.ExitWriteLock();
}
});
}
finally
{
_lock.ExitWriteLock();
}
}
}

Expand Down

0 comments on commit 1f2f4f4

Please sign in to comment.