一、模型背景
有时,代码需要交个其他线程处理,也不关心执行的进度,但是关心执行的顺序。
二、代码实现
public class ThreadTaskChanel : IDisposable { // 创建任务队列 private ConcurrentQueue<Action> _taskQueue = new ConcurrentQueue<Action>(); // 创建事件 private AutoResetEvent _taskAvailableEvent = new AutoResetEvent(false); private Thread _thread; public ThreadTaskChanel() { _thread = new Thread(() => { while (true) { if (_taskQueue.IsEmpty) _taskAvailableEvent.WaitOne(); Action task; if (_taskQueue.TryDequeue(out task)) { try { task(); } catch { } } } }); _thread.IsBackground = true; _thread.DisableComObjectEagerCleanup(); } ~ThreadTaskChanel() { Dispose(); } public void Start() { _thread?.Start(); } public void Stop() { try { _thread?.Abort(); } catch { } } public void PushToWork(Action action) { _taskQueue.Enqueue(action); _taskAvailableEvent.Set(); } public void Dispose() { Stop(); } }
三、调用
ThreadTaskChanel threadTaskChanel = new ThreadTaskChanel(); threadTaskChanel.Start(); while (true) { threadTaskChanel.PushToWork(() => { Console.WriteLine($"{DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss")} working..."); }); Thread.Sleep(1000); } }
标签:thread,ThreadTaskChanel,void,taskQueue,任务,线程,new,public,推入 From: https://www.cnblogs.com/xietianjiao/p/18277555