Don't use ThreadStatic in Helpers

This commit is contained in:
Garry Newman 2020-05-07 11:47:46 +01:00
parent 04d1c86954
commit b813ee7a17

View File

@ -9,24 +9,21 @@ namespace Steamworks
{ {
public const int MemoryBufferSize = 1024 * 32; public const int MemoryBufferSize = 1024 * 32;
[ThreadStatic] private static IntPtr[] MemoryPool; private static IntPtr[] MemoryPool = new IntPtr[]
[ThreadStatic] private static int MemoryPoolIndex; {
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize ),
Marshal.AllocHGlobal( MemoryBufferSize )
};
private static int MemoryPoolIndex;
public static unsafe IntPtr TakeMemory() 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];
for ( int i = 0; i < MemoryPool.Length; i++ )
MemoryPool[i] = Marshal.AllocHGlobal( MemoryBufferSize );
}
MemoryPoolIndex++; MemoryPoolIndex++;
if ( MemoryPoolIndex >= MemoryPool.Length ) if ( MemoryPoolIndex >= MemoryPool.Length )
MemoryPoolIndex = 0; MemoryPoolIndex = 0;
@ -36,10 +33,11 @@ namespace Steamworks
return take; return take;
} }
}
[ThreadStatic] private static byte[][] BufferPool; private static byte[][] BufferPool = new byte[4][];
[ThreadStatic] private static int BufferPoolIndex; private static int BufferPoolIndex;
/// <summary> /// <summary>
/// Returns a buffer. This will get returned and reused later on. /// Returns a buffer. This will get returned and reused later on.
@ -47,21 +45,16 @@ namespace Steamworks
/// </summary> /// </summary>
public static byte[] TakeBuffer( int minSize ) public static byte[] TakeBuffer( int minSize )
{ {
if ( BufferPool == null ) lock ( BufferPool )
{ {
//
// The pool has 4 items.
//
BufferPool = new byte[4][];
for ( int i = 0; i < BufferPool.Length; i++ )
BufferPool[i] = new byte[ 1024 * 128 ];
}
BufferPoolIndex++; BufferPoolIndex++;
if ( BufferPoolIndex >= BufferPool.Length ) if ( BufferPoolIndex >= BufferPool.Length )
BufferPoolIndex = 0; BufferPoolIndex = 0;
if ( BufferPool[BufferPoolIndex] == null )
BufferPool[BufferPoolIndex] = new byte[1024 * 256];
if ( BufferPool[BufferPoolIndex].Length < minSize ) if ( BufferPool[BufferPoolIndex].Length < minSize )
{ {
BufferPool[BufferPoolIndex] = new byte[minSize + 1024]; BufferPool[BufferPoolIndex] = new byte[minSize + 1024];
@ -69,6 +62,7 @@ namespace Steamworks
return BufferPool[BufferPoolIndex]; return BufferPool[BufferPoolIndex];
} }
}
internal unsafe static string MemoryToString( IntPtr ptr ) internal unsafe static string MemoryToString( IntPtr ptr )
{ {