Added Thread enforcers

This commit is contained in:
2026-01-25 13:49:05 +00:00
parent 24820fe646
commit abe3a4149b
4 changed files with 57 additions and 7 deletions

View File

@@ -0,0 +1,43 @@
using System.Runtime.CompilerServices;
using System.Threading;
using UnityEngine;
using System;
namespace PashaBibko.Pacore.Threading
{
public static partial class ThreadSafe
{
private static SynchronizationContext MainThreadContext { get; set; }
public class IncorrectThreadException : Exception
{
public IncorrectThreadException(string message)
: base(message)
{ }
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
private static void CaptureMainThreadContext()
{
MainThreadContext = SynchronizationContext.Current;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void EnforceMainThread()
{
if (SynchronizationContext.Current != MainThreadContext)
{
throw new IncorrectThreadException("Main thread function was called on a background thread");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void EnforceBackgroundThread()
{
if (SynchronizationContext.Current == MainThreadContext)
{
throw new IncorrectThreadException("Background thread function was called on the main thread");
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a4aad0735c2147beb2b087872fe4c364
timeCreated: 1769347995

View File

@@ -5,7 +5,7 @@ using System;
namespace PashaBibko.Pacore.Threading
{
public static class ThreadSafe
public static partial class ThreadSafe
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Try([NotNull] Action action, Action final = null)

View File

@@ -1,6 +1,8 @@
using System;
using System.Threading;
using PashaBibko.Pacore.Attributes;
using PashaBibko.Pacore.DevTools;
using PashaBibko.Pacore.Threading;
using UnityEngine;
[CreateInstanceOnStart] public class TestMonoBehaviour : MonoBehaviour
@@ -22,11 +24,13 @@ using UnityEngine;
[InspectorCallable("Test button")] public void LogTestValue()
{
Debug.Log($"Test value [{Test}]");
}
[InspectorCallable("Other Test button")] public void DontLogTestValue()
try
{
Debug.Log("Test");
ThreadSafe.EnforceBackgroundThread();
}
catch (Exception err)
{
Debug.LogError(err.Message);
}
}
}