Skip to content

Instantly share code, notes, and snippets.

@FlaShG
Last active October 28, 2018 20:09
Show Gist options
  • Save FlaShG/f2eb11838611d60e9649b6aa88034461 to your computer and use it in GitHub Desktop.
Save FlaShG/f2eb11838611d60e9649b6aa88034461 to your computer and use it in GitHub Desktop.
Small classes that allow for comfortably executing a single thread or a threadpool task in a coroutine.
using UnityEngine;
using System;
using System.Threading;
/// <summary>
/// Orders the Threadpool to perform an action and waits until it's done.
/// Use for short actions that maybe are performed more often.
/// </summary>
public class CoroutinePoolThread : CustomYieldInstruction
{
private volatile bool isDone;
public CoroutinePoolThread(Action action)
{
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
action();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
finally
{
this.isDone = true;
}
});
}
public override bool keepWaiting
{
get
{
return !isDone;
}
}
}
using UnityEngine;
using System;
using System.Threading;
/// <summary>
/// Starts a single thread and waits until it's done.
/// Use for single actions that might take a while.
/// </summary>
public class CoroutineThread : CustomYieldInstruction
{
private Thread thread;
public CoroutineThread(Action action)
{
thread = new Thread(new ThreadStart(action));
thread.Start();
}
public override bool keepWaiting
{
get
{
return thread.IsAlive;
}
}
public void Abort()
{
thread.Abort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment