(에센스) 2020년 6월 27일 C#라이브러리 작업 대기열 도움말 클래스

using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace Core.Util { /// /// /// public class TaskQueue { #region /// /// /// : 1ms /// public TaskQueue() { _timeSpan = TimeSpan.Zero; Start(); } /// /// /// : /// /// public TaskQueue(TimeSpan timeSpan) { _timeSpan = timeSpan; Start(); } #endregion #region Semaphore _semaphore { get; } = new Semaphore(0, int.MaxValue); //Semaphore , private void Start() { Task.Factory.StartNew(() => { while (_isRun) { try { _semaphore.WaitOne(); bool success = _taskList.TryDequeue(out Action task); if (success) { task?.Invoke(); } if (_timeSpan != TimeSpan.Zero) Thread.Sleep(_timeSpan); } catch (Exception ex) { HandleException?.Invoke(ex); } } }, TaskCreationOptions.LongRunning); } private bool _isRun { get; set; } = true; private TimeSpan _timeSpan { get; set; } private ConcurrentQueue<Action> _taskList { get; } = new ConcurrentQueue<Action>(); #endregion #region public void Stop() { _isRun = false; } public void Enqueue(Action task) { _taskList.Enqueue(task); _semaphore.Release(); } public Action<Exception> HandleException { get; set; } #endregion } }

좋은 웹페이지 즐겨찾기