Actually fix concurrency in tests this time

pull/1002/head
Tyrrrz 2 years ago
parent d5848bebc6
commit 1fc27fd5c4

@ -1,9 +1,11 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
@ -18,6 +20,8 @@ namespace DiscordChatExporter.Cli.Tests.Infra;
public static class ExportWrapper
{
private static readonly ConcurrentDictionary<string, SemaphoreSlim> Locks = new();
private static readonly string DirPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Directory.GetCurrentDirectory(),
"ExportCache"
@ -37,6 +41,12 @@ public static class ExportWrapper
}
private static async ValueTask<string> ExportAsync(Snowflake channelId, ExportFormat format)
{
// Lock separately for each channel and format
var channelLock = Locks.GetOrAdd($"{channelId}_{format}", _ => new SemaphoreSlim(1, 1));
await channelLock.WaitAsync();
try
{
var fileName = channelId.ToString() + '.' + format.GetFileExtension();
var filePath = Path.Combine(DirPath, fileName);
@ -55,6 +65,11 @@ public static class ExportWrapper
return await File.ReadAllTextAsync(filePath);
}
finally
{
channelLock.Release();
}
}
public static async ValueTask<IHtmlDocument> ExportAsHtmlAsync(Snowflake channelId) => Html.Parse(
await ExportAsync(channelId, ExportFormat.HtmlDark)

Loading…
Cancel
Save