上篇介绍了线程池多任务处理的脚本实现类。本篇介绍ThreadWaitHelper.cs类:作用是让非主线程休眠的工具类的实现。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
/*
* Author:W
* 线程休眠等待处理工具
* 【注意:只能休眠非主线程】
*/
namespace W.GameFramework.MultiThread
{
public class ThreadWaitHelper
{
/// <summary>
/// 让线程休眠特定秒数
/// </summary>
/// <param name="seconds"></param>
public static void WaitForSeconds(float seconds)
{
if (MainThreadHelper.CheckIsMainThread())
{
Debug.LogError("不允许休眠主线程");
return;
}
if (!UnityAppMonitor.Instance.Running)
return;
Thread.Sleep((int)Mathf.Max(1, Mathf.Round(seconds * 1000f)));
//如果游戏App不处于活跃状态,则让线程间歇性休眠
while (!UnityAppMonitor.Instance.Active)
Thread.Sleep(5);
}
/// <summary>
/// 让线程休眠特定的帧数
/// 让线程休眠休眠特定毫秒后,在等待的帧数内, 继续让线程休眠特定时间
/// </summary>
/// <param name="waitFrames"></param>
/// <param name="sleepTime"></param>
public static void WaitForNextFrame(int waitFrames = 1, int sleepTime = 5)
{
if (waitFrames > 0)
{
if (MainThreadHelper.CheckIsMainThread())
{
Debug.LogError("不允许休眠主线程");
return;
}
int startFrame = ThreadManager.Instance.CurFrame;
if (!UnityAppMonitor.Instance.Running)
return;
Thread.Sleep(sleepTime);
while (!UnityAppMonitor.Instance.Active || startFrame + waitFrames >= ThreadManager.Instance.CurFrame)
Thread.Sleep(sleepTime);
}
}
}
}