C# Executor

原创
2021/08/10 17:01
阅读数 191
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Timers;

namespace ConsoleApplication2
{
    public class Executor
    {
        private ConcurrentQueue<Action> cq = new ConcurrentQueue<Action>();

        public Executor(int threadCount)
        {
            for (int i = 0; i <= threadCount; i++)
            {
                Thread obj = new Thread(pickRunable);
                obj.Start();
            }
        }

        public void postRunable(Action action)
        {
            cq.Enqueue(action);
        }

        public void postRunable(Action action, long ms)
        {
            System.Timers.Timer timer = new System.Timers.Timer(ms);
            timer.Elapsed += (sender, args) => { postRunable(action); };
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();
        }

        public void postRunable(Action action, long ms, bool repeat)
        {
            System.Timers.Timer timer = new System.Timers.Timer(ms);
            timer.Elapsed += (sender, args) =>
            {
                timer.Stop();
                if (repeat)
                {
                    postRunable(action);
                    postRunable(action, ms, true);
                }
                else
                {
                    postRunable(action);
                }
            };
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();
        }

        private void pickRunable()
        {
            Thread.CurrentThread.Name = "excutor thread";
            for (;;)
            {
                Action action;
                if (cq.TryDequeue(out action))
                {
                    action();
                }
            }
        }
    }
}
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using ConsoleApplication2;

class CQ_EnqueueDequeuePeek
{
    static void Main()
    {
        Executor executor = new Executor(1);
        executor.postRunable(() => { Console.WriteLine("action after 1 second"); }, 1000, false);
        executor.postRunable(() => { Console.WriteLine("action repeat every 1 second"); }, 1000, true);
        Thread.Sleep(1111111111);
    }
}

 

展开阅读全文
cq
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部