Skip to content

Instantly share code, notes, and snippets.

@m2wasabi
Created July 16, 2017 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m2wasabi/aa1227bf26dc5dca3a2112228b05c8b0 to your computer and use it in GitHub Desktop.
Save m2wasabi/aa1227bf26dc5dca3a2112228b05c8b0 to your computer and use it in GitHub Desktop.
\Assets\FrostweepGames\GCSpeechRecognition\Scripts\Core\Managers\ThreadManager.cs
using System;
using System.Collections.Generic;
#if UNITY_WSA && NETFX_CORE
using System.Threading.Tasks;
#else
using System.Threading;
#endif
namespace FrostweepGames.Plugins.GoogleCloud.SpeechRecognition
{
public class ThreadManager : IDisposable
{
#if UNITY_WSA && NETFX_CORE
private volatile List<Task> _threads;
#else
private volatile List<Thread> _threads;
#endif
private volatile Queue<Action> _mainThreadActions;
public ThreadManager()
{
#if UNITY_WSA && NETFX_CORE
_threads = new List<Task>();
#else
_threads = new List<Thread>();
#endif
_mainThreadActions = new Queue<Action>();
}
public void Update()
{
if (_mainThreadActions.Count > 0)
{
for (int i = 0; i < _mainThreadActions.Count; i++)
_mainThreadActions.Dequeue().Invoke();
}
}
public void Dispose()
{
AbortAllThreads();
}
public void RunInNewThread(Action method)
{
#if UNITY_WSA && NETFX_CORE
Task thread = new Task(method);
#else
Thread thread = new Thread(new ThreadStart(method));
#endif
thread.Start();
_threads.Add(thread);
}
public void RunInMainThread(Action method)
{
_mainThreadActions.Enqueue(method);
}
/// <summary>
/// Abort all threads.
/// be sure to use it if threads count > 0 and if app will be closing
/// </summary>
public void AbortAllThreads()
{
foreach (var thread in _threads)
{
#if UNITY_IOS
thread.Interrupt();
#elif UNITY_WSA && NETFX_CORE
#else
thread.Abort();
#endif
}
_threads.Clear();
_mainThreadActions.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment