c# unity 异步任务队列

异步任务队列,十分好用

using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

/// <summary>
/// 异步任务队列
/// </summary>
public class AsyncQueueTask
{
    public delegate Task<bool> TaskDel(object data);
    private bool isWait;
    
    //方法队列
    Queue<TaskDel> taskQueue = new Queue<TaskDel>();
    //参数队列
    Queue<object> paraQueue = new Queue<object>();
    
    
    
    /// <summary>
    /// 调用这个即可
    /// </summary>
    /// <param name="ac">方法</param>
    /// <param name="data">参数</param>
    public void AddQueueTask(TaskDel ac, object data)
    {
        Debug.Log("入队");
        taskQueue.Enqueue(ac);
        paraQueue.Enqueue(data);
        StartTask();
    }
    
    async void StartTask()
    {
        if (!isWait && taskQueue.Count != 0)
        {
            isWait = true;
            await taskQueue.Peek()(paraQueue.Peek());
            Debug.Log("出队");
            taskQueue.Dequeue();
            paraQueue.Dequeue();
            isWait = false;
            StartTask();
        }
    }
}

 

posted @ 2021-01-05 15:02  三页菌  阅读(609)  评论(0编辑  收藏  举报