using Cognex.VisionPro; using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace ConVX.VXData { public class DataPostbox { #region 字段 /// /// 图像队列:来存储数据信封(CogImage8Grey)的队列。 /// private ConcurrentQueue _queue; /// /// 判断线程状态 /// //private AutoResetEvent _autoReset = null; /// /// 线程 /// private Task _task; /// /// 控制任务启动 /// private CancellationTokenSource RuningToken; #endregion #region 事件 /// /// 当有信件被派发时触发的事件。 /// public event Action DeliverLetterEvent; /// /// 当发生错误时触发的事件。 /// public event Action ErrorEvent; #endregion #region 公开的方法 /// /// 构造函数 /// public DataPostbox() { _queue = new ConcurrentQueue(); } /// /// 启动派发 /// public void Start() { RuningToken = new CancellationTokenSource();//创建启动 _task = new Task(() => EnvelopeProcessing(), RuningToken.Token); _task.Start();//线程启动 } /// /// 停止派发 /// public async void Stop() { try { RuningToken.Cancel(); await _task; } catch (OperationCanceledException ex) { _task.Dispose(); _task = null; } } /// /// 邮寄信件 /// /// 信息信件 public void Mailing(CogImage8Grey envelope) { _queue.Enqueue(envelope); } #endregion #region 数据处理线程 private void EnvelopeProcessing() { while (!RuningToken.IsCancellationRequested) { if (_queue.IsEmpty) { Thread.Sleep(1); } else { try { CogImage8Grey envelope; if (_queue.TryDequeue(out envelope)) { DeliverLetterEvent(envelope); } } catch (Exception ex) { ErrorEvent(string.Format("数据队列出队失败,原因:{0}", ex.Message.ToString())); } } } } #endregion } }