#if NETFX_CORE
#define TASK_AVAILABLE
using System.Threading.Tasks;
#endif
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
namespace DigitalRuby.Threading
{
public class EZThread : MonoBehaviour
{
///
/// Encapsulates a fully running thread
///
public class EZThreadRunner
{
private bool running = true;
private Action action;
private void ThreadFunction()
{
while (running)
{
action();
}
}
private void ThreadFunctionSync()
{
while (running)
{
action();
SyncEvent.WaitOne(100);
}
}
///
/// Constructor
///
/// Action
/// Whether to sync with the main thread update loop
internal EZThreadRunner(Action action, bool synchronizeWithUpdate)
{
this.action = action;
this.running = true;
if (synchronizeWithUpdate)
{
SyncEvent = new System.Threading.AutoResetEvent(true);
}
#if TASK_AVAILABLE
if (synchronizeWithUpdate)
{
Task.Factory.StartNew(ThreadFunctionSync);
}
else
{
Task.Factory.StartNew(ThreadFunction);
}
#else
WaitCallback w;
if (synchronizeWithUpdate)
{
w = new WaitCallback((s) => ThreadFunctionSync());
}
else
{
w = new WaitCallback((s) => ThreadFunction());
}
ThreadPool.QueueUserWorkItem(w);
#endif
}
///
/// Stop and remove the thread
///
public void Stop()
{
running = false;
}
public AutoResetEvent SyncEvent { get; private set; }
}
private static GameObject singletonObject;
private static EZThread singleton;
private readonly List> mainThreadActions = new List>();
private readonly Queue>> mainThreadCompletions = new Queue>>();
private readonly List threads = new List();
private static void EnsureCreated()
{
if (singleton != null)
{
return;
}
singletonObject = new GameObject("EZTHREAD");
singletonObject.hideFlags = HideFlags.HideAndDontSave;
singleton = singletonObject.AddComponent();
GameObject.DontDestroyOnLoad(singleton);
#if !TASK_AVAILABLE
System.Threading.ThreadPool.SetMinThreads(Environment.ProcessorCount, Environment.ProcessorCount);
System.Threading.ThreadPool.SetMaxThreads(Environment.ProcessorCount, Environment.ProcessorCount);
#endif
}
private static void InternalExecute(Func