From b813ee7a17a7445a9d758e3f677664948eb30d21 Mon Sep 17 00:00:00 2001 From: Garry Newman Date: Thu, 7 May 2020 11:47:46 +0100 Subject: [PATCH] Don't use ThreadStatic in Helpers --- Facepunch.Steamworks/Utility/Helpers.cs | 74 ++++++++++++------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/Facepunch.Steamworks/Utility/Helpers.cs b/Facepunch.Steamworks/Utility/Helpers.cs index 65dd715..5801905 100644 --- a/Facepunch.Steamworks/Utility/Helpers.cs +++ b/Facepunch.Steamworks/Utility/Helpers.cs @@ -9,37 +9,35 @@ namespace Steamworks { public const int MemoryBufferSize = 1024 * 32; - [ThreadStatic] private static IntPtr[] MemoryPool; - [ThreadStatic] private static int MemoryPoolIndex; + private static IntPtr[] MemoryPool = new IntPtr[] + { + Marshal.AllocHGlobal( MemoryBufferSize ), + Marshal.AllocHGlobal( MemoryBufferSize ), + Marshal.AllocHGlobal( MemoryBufferSize ), + Marshal.AllocHGlobal( MemoryBufferSize ) + }; + private static int MemoryPoolIndex; public static unsafe IntPtr TakeMemory() { - if ( MemoryPool == null ) + lock ( MemoryPool ) { - // - // The pool has 4 items. This should be safe because we shouldn't really - // ever be using more than 2 memory pools - // - MemoryPool = new IntPtr[4]; + MemoryPoolIndex++; - for ( int i = 0; i < MemoryPool.Length; i++ ) - MemoryPool[i] = Marshal.AllocHGlobal( MemoryBufferSize ); + if ( MemoryPoolIndex >= MemoryPool.Length ) + MemoryPoolIndex = 0; + + var take = MemoryPool[MemoryPoolIndex]; + + ((byte*)take)[0] = 0; + + return take; } - - MemoryPoolIndex++; - if ( MemoryPoolIndex >= MemoryPool.Length ) - MemoryPoolIndex = 0; - - var take = MemoryPool[MemoryPoolIndex]; - - ((byte*)take)[0] = 0; - - return take; } - [ThreadStatic] private static byte[][] BufferPool; - [ThreadStatic] private static int BufferPoolIndex; + private static byte[][] BufferPool = new byte[4][]; + private static int BufferPoolIndex; /// /// Returns a buffer. This will get returned and reused later on. @@ -47,27 +45,23 @@ namespace Steamworks /// public static byte[] TakeBuffer( int minSize ) { - if ( BufferPool == null ) + lock ( BufferPool ) { - // - // The pool has 4 items. - // - BufferPool = new byte[4][]; + BufferPoolIndex++; - for ( int i = 0; i < BufferPool.Length; i++ ) - BufferPool[i] = new byte[ 1024 * 128 ]; + if ( BufferPoolIndex >= BufferPool.Length ) + BufferPoolIndex = 0; + + if ( BufferPool[BufferPoolIndex] == null ) + BufferPool[BufferPoolIndex] = new byte[1024 * 256]; + + if ( BufferPool[BufferPoolIndex].Length < minSize ) + { + BufferPool[BufferPoolIndex] = new byte[minSize + 1024]; + } + + return BufferPool[BufferPoolIndex]; } - - BufferPoolIndex++; - if ( BufferPoolIndex >= BufferPool.Length ) - BufferPoolIndex = 0; - - if ( BufferPool[BufferPoolIndex].Length < minSize ) - { - BufferPool[BufferPoolIndex] = new byte[minSize + 1024]; - } - - return BufferPool[BufferPoolIndex]; } internal unsafe static string MemoryToString( IntPtr ptr )