From a8d3d2773eff9d9cea6018b7d208a80984f06f6d Mon Sep 17 00:00:00 2001 From: Kamron Batman <3953314+kamronbatman@users.noreply.github.com> Date: Sun, 2 Jun 2024 15:02:47 -0700 Subject: [PATCH] fix: Fixes libdeflate threading issue (#1813) --- Projects/Server/Compression/Deflate.cs | 14 +++----------- Projects/Server/Main.cs | 5 +++++ 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/Projects/Server/Compression/Deflate.cs b/Projects/Server/Compression/Deflate.cs index 6810ef7d6..deec8eb18 100644 --- a/Projects/Server/Compression/Deflate.cs +++ b/Projects/Server/Compression/Deflate.cs @@ -20,16 +20,8 @@ namespace Server.Compression; public static class Deflate { - public static LibDeflateBinding Standard { get; } + [ThreadStatic] + private static LibDeflateBinding _standard; - static Deflate() - { - Standard = new LibDeflateBinding(); - AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; - } - - private static void CurrentDomain_ProcessExit(object sender, EventArgs e) - { - Standard.Dispose(); - } + public static LibDeflateBinding Standard => _standard ??= new LibDeflateBinding(); } diff --git a/Projects/Server/Main.cs b/Projects/Server/Main.cs index d245ebcb1..e62a715a2 100644 --- a/Projects/Server/Main.cs +++ b/Projects/Server/Main.cs @@ -25,6 +25,7 @@ using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Server.Compression; using Server.Json; using Server.Logging; using Server.Network; @@ -465,6 +466,10 @@ public static class Core Console.CancelKeyPress += Console_CancelKeyPressed; + // LibDeflate is not thread safe, so we need to create a new instance for each thread + var standard = Deflate.Standard; + AppDomain.CurrentDomain.ProcessExit += (_, _) => standard.Dispose(); + ServerConfiguration.Load(); logger.Information("Running on {Framework}", RuntimeInformation.FrameworkDescription);