Skip to content

Instantly share code, notes, and snippets.

@marcteys
Created July 3, 2018 12:41
Show Gist options
  • Save marcteys/a2a6a3b88f47d31a8ac77e4dffce4e6b to your computer and use it in GitHub Desktop.
Save marcteys/a2a6a3b88f47d31a8ac77e4dffce4e6b to your computer and use it in GitHub Desktop.
Simple Thread Unity
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class SimpleThread : MonoBehaviour
{
Action threadActionCallback = null;
Action mainActionCallback = null;
Thread ChildThread = null;
EventWaitHandle ChildThreadWait = new EventWaitHandle(true, EventResetMode.ManualReset);
EventWaitHandle MainThreadWait = new EventWaitHandle(true, EventResetMode.ManualReset);
void ChildThreadLoop()
{
ChildThreadWait.Reset();
ChildThreadWait.WaitOne();
while (true)
{
ChildThreadWait.Reset();
if (threadActionCallback == null)
{
// There is no callback action to do on the small Thread
mainActionCallback = () =>
{
Debug.Log("This is launched from the main Thread");
};
}
else
{
try
{
threadActionCallback(); // Launching CallBack
}
catch (Exception e)
{
Debug.Log(e);
}
threadActionCallback = null;
}
//Wait for the mainThrea to finish the current Update
WaitHandle.SignalAndWait(MainThreadWait, ChildThreadWait);
}
}
void Awake()
{
ChildThread = new Thread(ChildThreadLoop);
ChildThread.Start();
}
void Update()
{
MainThreadWait.WaitOne();
MainThreadWait.Reset();
// Send something to do in the child Thread
threadActionCallback = () => Debug.Log("Do stuff on the child thread"); // Call a Unity thing inside the thread
//
if (mainActionCallback != null)
{
try
{
mainActionCallback(); // Launching callback from childThread in main Thread
}
catch (Exception e)
{
Debug.Log(e);
}
mainActionCallback = null;
}
ChildThreadWait.Set();
}
public void OnApplicationQuit()
{
ChildThreadWait.Close();
MainThreadWait.Close();
Debug.Log("Stopping Thread");
try
{
ChildThread.Abort(); // <= No cool but Unity might freeze otherwise
}
catch (Exception e)
{
Debug.Log(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment