c# 简单任务控制
public class taskTest { private int _taskNums = 100; //初始化100个任务 private Semaphore _semaphpre; //信号量控制任务并发的数量 private const int _max = 5; //最大任务并发数 private Hashtable _taskList = Hashtable.Synchronized(new Hashtable()); //任务集合 private string _taskName = "task_"; public EventHandler evt; private TaskStatus _mStaus; //主任务状态 private CancellationTokenSource _cts; private ManualResetEvent _mre; public taskTest(){ _semaphpre = new Semaphore(_max, _max); _cts = new CancellationTokenSource(); _mre = new ManualResetEvent(false); } public void startTask(){ _mre.Set(); Task.Factory.StartNew(()=>MainTaskControl()); _mStaus = TaskStatus.Running; } private void MainTaskControl(){ for (int i = 0; i < _taskNums; i++) { if (_cts.Token.IsCancellationRequested) { _mStaus = TaskStatus.Stopped; break; } _mre.WaitOne(); _semaphpre.WaitOne(); string tmpName = _taskName + i.ToString(); taskInfoMsg msg = new taskInfoMsg(tmpName, TaskStatus.Running.ToString(), i); Task t = Task.Factory.StartNew(()=>tasktask(msg), _cts.Token); _taskList.Add(tmpName, t); } } public void Close(){ if(_semaphpre != null){ _semaphpre.Close(); } if(_cts != null){ _cts.Dispose(); } if(_mre != null){ _mre.Close(); } } private async Task tasktask(taskInfoMsg msg){ int count = 0; while (count < 5) { // if(_cts.Token.IsCancellationRequested){ break; //跳出循环 } if(_mStaus == TaskStatus.Suspend){ evt(this, new taskInfoMsg(msg._taskName, TaskStatus.Suspend.ToString(), msg._taskID)); } _mre.WaitOne(); //任务暂停控制 evt(this, new taskInfoMsg(msg._taskName, TaskStatus.Running.ToString(), msg._taskID)); await Task.Delay(TimeSpan.FromSeconds(1)); // 模拟耗时操作 count ++; } _semaphpre.Release(); evt(this, new taskInfoMsg(msg._taskName, TaskStatus.Stopped.ToString(), msg._taskID)); } public int GetLiveTaskCount(){ if(_taskList.IsSynchronized){ return _taskList.Count; } return _taskList.Count; } public void suspendTask(){ _mre.Reset(); _mStaus = TaskStatus.Suspend; } public void ContinueTask(){ _mre.Set(); _mStaus = TaskStatus.Running; } public void CancelTask(){ if(_mStaus == TaskStatus.Running || _mStaus == TaskStatus.Suspend){ _cts.Cancel(); } } } enum TaskStatus{ Running, Stopped, Suspend } public class taskInfoMsg : EventArgs{ public string _taskName{get; set;} public string _taskStatus{get; set;} public int _taskID{get; set;} public taskInfoMsg(string taskName, string taskStatus, int taskID){ this._taskName = taskName; this._taskStatus = taskStatus; this._taskID = taskID; } } }