Last active
October 28, 2018 20:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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