namespace Sandbox;
///
/// Provides utilities for working with threads, particularly for identifying
/// and asserting code is running on the main thread.
///
public static class ThreadSafe
{
[ThreadStatic]
static bool isMainThread;
///
/// Gets the current thread's managed thread ID.
///
public static int CurrentThreadId => System.Threading.Thread.CurrentThread.ManagedThreadId;
///
/// Gets the current thread's name, or null if unnamed.
///
public static string CurrentThreadName => System.Threading.Thread.CurrentThread.Name;
///
/// Returns true if currently executing on the main thread.
///
public static bool IsMainThread => isMainThread;
///
/// Marks the current thread as the main thread.
/// This is called internally during engine initialization.
///
internal static void MarkMainThread()
{
isMainThread = true;
}
///
/// Throws an exception if not called from the main thread.
/// Useful for enforcing thread safety on main-thread-only APIs.
///
/// Automatically filled with the calling method name
/// Thrown if not on the main thread
public static void AssertIsMainThread( [System.Runtime.CompilerServices.CallerMemberName] string memberName = "" )
{
if ( IsMainThread ) return;
throw new System.Exception( $"{memberName} must be called on the main thread!" );
}
///
/// Throws an exception if called from the main thread.
/// Useful for enforcing that blocking operations don't run on the main thread.
///
/// Thrown if on the main thread
public static void AssertIsNotMainThread()
{
if ( !IsMainThread ) return;
throw new System.Exception( "This function must not be called on the main thread!" );
}
}