chip-game/Assets/Scripts/Inputs/ComSystem/UnityMainThreadDispatcher.cs

59 lines
1.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Concurrent;
using System.Threading.Tasks;
using UnityEngine;
using System;
public class UnityMainThreadDispatcher : MonoBehaviour
{
private static UnityMainThreadDispatcher instance;
private readonly ConcurrentQueue<Action> actionQueue = new ConcurrentQueue<Action>();
public static UnityMainThreadDispatcher Instance
{
get
{
if (instance == null)
{
var go = new GameObject("UnityMainThreadDispatcher");
DontDestroyOnLoad(go);
instance = go.AddComponent<UnityMainThreadDispatcher>();
}
return instance;
}
}
// Для синхронного выполнения
public void Enqueue(Action action)
{
actionQueue.Enqueue(action);
}
// Для асинхронного выполнения с ожиданием
public Task EnqueueAsync(Action action)
{
var tcs = new TaskCompletionSource<bool>();
actionQueue.Enqueue(() =>
{
try
{
action();
tcs.SetResult(true);
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
private void Update()
{
while (actionQueue.TryDequeue(out var action))
{
action();
}
}
}