Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- namespace iGP
- {
- public class ThreadManager
- {
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- //Public nested data structures declaration
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- public delegate void ThreadCall( object data, Action onResult );
- private struct ThreadParams
- {
- public ThreadCall threadCall;
- public object data;
- public Action onResult;
- public ThreadParams( ThreadCall threadCall, object data, Action onResult )
- {
- this.threadCall = threadCall;
- this.data = data;
- this.onResult = onResult;
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- //Public methods
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- public static void CalledOnUnityMainThread()
- {
- while (onResultQueue.Count > 0)
- {
- onResultQueue.Dequeue().Invoke();
- }
- }
- public void Run( ThreadCall threadCall, object data, Action onResult )
- {
- var thread = new Thread(ThreadFunction);
- ThreadParams threadParams = new ThreadParams(threadCall, data, onResult);
- thread.Start(threadParams);
- thread.IsBackground = true;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- //Private methods
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- private static void ThreadFunction( object state )
- {
- ThreadParams threadParams;
- try
- {
- threadParams = (ThreadParams) state;
- }
- catch
- {
- return;
- }
- threadParams.threadCall( threadParams.data, threadParams.onResult );
- lock(lockObj)
- {
- onResultQueue.Enqueue(threadParams.onResult);
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- //Private fields
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- private static Queue<Action> onResultQueue = new Queue<Action>();
- private static System.Object lockObj = new System.Object();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement