public void Dispatcher(ICoroutineUnit unit) { if (unit != null) { var newid = System.Threading.Interlocked.Increment(ref id); CoroutineUnitBag bag = new CoroutineUnitBag(newid, unit); var work = works[newid % workthreads]; work.Add(bag); } }
public void Interrupt(CoroutineUnitBag forUnit) { var time = this.turnstart; if (forUnit != null && forUnit == currentUnit && !forUnit.HasError) { forUnit.HasError = true; forUnit.Error = new TimeoutException("检查到长时间运行任务需要中断执行,线程号:" + this.thread.ManagedThreadId + ",任务id:" + forUnit.Id + "," + forUnit.CUnit.ToString() + ",执行时间:" + (DateTime.Now.Subtract(time).TotalMilliseconds + ",还有任务数:" + this.units.Count)); lock (this) { this.thread.Abort(); } } }
public void Add(CoroutineUnitBag bag) { if (bag != null) { lock (unitstemp) { unitstemp.Add(bag); } if (!running) { lock (this) { if (!running) { running = true; MakeThread(); } } } } }
private void Loop() { bool isfirst = true; bool isdone = true; List <CoroutineUnitBag> leftlist = new List <CoroutineUnitBag>(); while (running) { DateTime timestart = DateTime.Now; lock (this) { turnstart = DateTime.MaxValue; currentUnit = null; if (!isfirst) { units = leftlist; leftlist = new List <CoroutineUnitBag>(); } else { isfirst = false; } lock (unitstemp) { units.AddRange(unitstemp); unitstemp.Clear(); } } if (units.Count == 0) { if (sleepms < maxsleepms) { Thread.Sleep(sleepms++); continue; } else { sleepms = 1; running = false; break; } } else { sleepms = 1; } foreach (var bag in units) { isdone = true; if (!bag.HasError) { turnstart = DateTime.Now; currentUnit = bag; bag.Exceute(); { try { if (!bag.IsDone() && !bag.IsSuccess()) { if (bag.IsTimeOut()) { throw new TimeoutException(); } isdone = false; } } catch (Exception ex) { bag.HasError = true; bag.Error = ex; isdone = true; } } } turnstart = DateTime.MaxValue; currentUnit = null; if (isdone) { try { bag.CallBack(new CoroutineCallBackEventArgs { CoroutineUnit = bag.CUnit, Error = bag.Error, HasError = bag.HasError }); } catch { } } else { leftlist.Add(bag); } } if (leftlist.Count > 0) { var ms = DateTime.Now.Subtract(timestart).TotalMilliseconds; Thread.Sleep((int)(100.0 / Math.Max(ms, 1) / maxCpu)); } } }