您最多选择25个主题
主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
65 行
1.7 KiB
65 行
1.7 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
|
|
namespace MetaCity.Core.Common
|
|
{
|
|
public static class ThreadingUtils
|
|
{
|
|
private static bool _initialised;
|
|
private static Thread _mainThread;
|
|
private static readonly List<Action> ActionsToRunOnMainThread = new();
|
|
|
|
public static void Initialise()
|
|
{
|
|
if (_initialised) return;
|
|
|
|
_initialised = true;
|
|
_mainThread = Thread.CurrentThread;
|
|
lock (ActionsToRunOnMainThread)
|
|
{
|
|
ActionsToRunOnMainThread.Clear();
|
|
}
|
|
}
|
|
|
|
public static void Destroy()
|
|
{
|
|
_initialised = false;
|
|
}
|
|
|
|
public static bool IsOnMainThread()
|
|
{
|
|
return _mainThread != null && _mainThread.Equals(Thread.CurrentThread);
|
|
}
|
|
|
|
public static void EnqueueActionForMainThread(Action action)
|
|
{
|
|
if (!_initialised) return;
|
|
|
|
lock (ActionsToRunOnMainThread)
|
|
{
|
|
ActionsToRunOnMainThread.Add(action);
|
|
}
|
|
}
|
|
|
|
public static void EnqueueActionForMainThreadOrRunRightNow(Action action)
|
|
{
|
|
if (!_initialised) return;
|
|
|
|
if (IsOnMainThread())
|
|
action();
|
|
else
|
|
EnqueueActionForMainThread(action);
|
|
}
|
|
|
|
public static void Update()
|
|
{
|
|
lock (ActionsToRunOnMainThread)
|
|
{
|
|
foreach (var action in ActionsToRunOnMainThread) action();
|
|
|
|
ActionsToRunOnMainThread.Clear();
|
|
}
|
|
}
|
|
}
|
|
}
|