接入一些sdk,有时候需要线程操作,推介一个
using UnityEngine;
using System.Collections.Generic;
using System;
using System.Threading;
public class ThreadHelper : MonoBehaviour
{
private static ThreadHelper Current;
private List<Action> actions = new List<Action>();
private static Thread mainThread;
public static bool IsMainThread()
{
return Thread.CurrentThread == mainThread;
}
// Use this for initialization
void Awake()
{
Current = this;
mainThread = Thread.CurrentThread;
}
// Update is called once per frame
void Update()
{
var currentActions = new List<Action>();
lock (actions)
{
currentActions.AddRange(actions);
foreach (var item in currentActions)
actions.Remove(item);
}
foreach (var action in currentActions)
{
action();
}
}
public static void QueueOnMainThread(Action action)
{
if(IsMainThread())
{
action();
return;
}
lock (Current.actions)
{
Current.actions.Add(action);
}
}
public static void QueueOnThreadPool(WaitCallback callBack, object state = null)
{
ThreadPool.QueueUserWorkItem(callBack, state);
}
}