Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.