Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

Commit ec382fb

Browse files
authored
Merge pull request #1680 from github/fixes/1677-guard-reads-and-writes
Guard when reading from/writing to metrics.json
2 parents 82b2b6d + 3b10f23 commit ec382fb

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/GitHub.VisualStudio/Services/UsageService.cs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public sealed class UsageService : IUsageService, IDisposable
2424

2525
readonly IGitHubServiceProvider serviceProvider;
2626
readonly IEnvironment environment;
27-
readonly SemaphoreSlim writeSemaphoreSlim = new SemaphoreSlim(1, 1);
27+
readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
2828

2929
string storePath;
3030
string userStorePath;
@@ -39,7 +39,7 @@ public UsageService(IGitHubServiceProvider serviceProvider, IEnvironment environ
3939

4040
public void Dispose()
4141
{
42-
writeSemaphoreSlim.Dispose();
42+
semaphoreSlim.Dispose();
4343
}
4444

4545
public async Task<Guid> GetUserGuid()
@@ -146,17 +146,26 @@ async Task Initialize()
146146

147147
async Task<string> ReadAllTextAsync(string path)
148148
{
149-
using (var s = File.OpenRead(path))
150-
using (var r = new StreamReader(s, Encoding.UTF8))
149+
// Avoid IOException when metrics updated multiple times in quick succession
150+
await semaphoreSlim.WaitAsync();
151+
try
152+
{
153+
using (var s = File.OpenRead(path))
154+
using (var r = new StreamReader(s, Encoding.UTF8))
155+
{
156+
return await r.ReadToEndAsync();
157+
}
158+
}
159+
finally
151160
{
152-
return await r.ReadToEndAsync();
161+
semaphoreSlim.Release();
153162
}
154163
}
155164

156165
async Task WriteAllTextAsync(string path, string text)
157166
{
158167
// Avoid IOException when metrics updated multiple times in quick succession
159-
await writeSemaphoreSlim.WaitAsync();
168+
await semaphoreSlim.WaitAsync();
160169
try
161170
{
162171
using (var s = new FileStream(path, FileMode.Create))
@@ -167,7 +176,7 @@ async Task WriteAllTextAsync(string path, string text)
167176
}
168177
finally
169178
{
170-
writeSemaphoreSlim.Release();
179+
semaphoreSlim.Release();
171180
}
172181
}
173182

0 commit comments

Comments
 (0)