47 lines
1.2 KiB
C#
47 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using UnityEngine;
|
|
|
|
namespace BrewMonster.Scripts.ChatUI
|
|
{
|
|
/// <summary>
|
|
/// Responsible for switching chat messages from background threads to Unity main thread.
|
|
/// Only handles chat related actions.
|
|
/// </summary>
|
|
public class ChatThreadDispatcher : MonoSingleton<ChatThreadDispatcher>
|
|
{
|
|
private static readonly ConcurrentQueue<Action> _queue = new ConcurrentQueue<Action>();
|
|
|
|
protected override void Awake()
|
|
{
|
|
base.Awake();
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called from ANY thread (network thread safe)
|
|
/// </summary>
|
|
public void Post(Action action)
|
|
{
|
|
if (action == null)
|
|
return;
|
|
|
|
_queue.Enqueue(action);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
while (_queue.TryDequeue(out var action))
|
|
{
|
|
try
|
|
{
|
|
action?.Invoke();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Debug.LogError($"ChatThreadDispatcher error: {e}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |