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

public class TaskQueueProcess<T>
{

    Task m_RunTask;
    ConcurrentQueue<T> m_Messages = new ConcurrentQueue<T>();
    AutoResetEvent auto = new AutoResetEvent(true);

    T message;
    Func<T, bool> m_Handler;

    bool m_Abort = false;

    public int queueCount => m_Messages == null ? 0 : m_Messages.Count;

    //处理间隔，ms
    int m_IntervalTime = 2000;

    public void Release()
    {
        this.m_Abort = true;
        m_Handler = null;
        m_Messages = null;
        auto = null;
    }

    public TaskQueueProcess(Func<T, bool> handler)
    {
        this.m_Handler = handler;
        m_RunTask = Task.Run(Process);
    }

    public TaskQueueProcess(Func<T, bool> handler,int intervalTime)
    {
        this.m_IntervalTime = intervalTime;
        this.m_Handler = handler;
        m_RunTask = Task.Run(Process);
    }

    public void Post(T message)
    {
        m_Messages.Enqueue(message);
    }

    public async Task Process()
    {
        while (true)
        {
            if (m_Abort)
            {
                m_RunTask.Dispose();
                m_RunTask = null;
                return;
            }

            message = default(T);
            if (m_Messages.TryDequeue(out message))
            {
                if (m_Handler.Invoke(message))
                {
                    auto.WaitOne();
                }
                await Task.Delay(this.m_IntervalTime);
            }
            else
            {
                auto.WaitOne();
            }
        }
    }

    public void Set(bool state)
    {
        if (!state)
        {
            Post(message);
        }
        auto.Set();
    }

}
