/// <summary> /// 添加任务 /// </summary> /// <param name="objectKey"></param> /// <param name="callback"></param> /// <param name="context"></param> public void AddTask(T objectKey, Action <T, String> callback, String context) { QueueTask <T> task = new QueueTask <T>(); task.ObjectKey = objectKey; task.Callback = callback; task.Context = context; // 加入任务执行队列 lock (_RunLocker) { _TaskRunQueue.Enqueue(task); } // 有生产,则通知执行线程(消费者) _WaitHandle.Set(); }
/// <summary> /// 任务执行线程主体 /// </summary> private void TaskRunning() { while (_Working) { QueueTask <T> task = null; lock (_RunLocker) { if (_TaskRunQueue.Count > 0) { task = _TaskRunQueue.Dequeue(); } } // 存在超时任务执行其回调 if (task != null) { task.Callback(task.ObjectKey, task.Context); } else { // 等待生产者通知 _WaitHandle.WaitOne(); } } }