Ejemplo n.º 1
0
 /// <summary>
 /// 添加一个计时器任务
 /// </summary>
 /// <param name="task">将执行的任务</param>
 /// <param name="time">任务执行时间 ms</param>
 public int AddSchedule(TimeTask task, long time)
 {
     lock (task)
     {
         Index++;
         long nowTime = DateTime.Now.Ticks;
         //当前时间+延时间隔ms
         nowTime += time / 10000;
         TimeTaskModel model = new TimeTaskModel(Index, nowTime, task);
         //将任务添加到任务字典
         mTaskDict.TryAdd(Index, model);
         return(Index);
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// 执行回调
 /// </summary>
 private void CallBack()
 {
     //线程锁,防止数据竞争
     lock (mRemoveList)
     {
         lock (mTaskDict)
         {
             TimeTaskModel model = null;
             //执行前将待移除的任务移除
             for (int i = 0; i < mRemoveList.Count; i++)
             {
                 mTaskDict.TryRemove(mRemoveList[i], out model);
             }
             mRemoveList.Clear();
             long       endTime  = DateTime.Now.Ticks;
             List <int> dkeyList = new List <int>(mTaskDict.Keys.ToList());
             for (int i = 0; i < dkeyList.Count; i++)
             {
                 //如果待执行的时间小于等于当前时间
                 if (mTaskDict[dkeyList[i]].Time <= endTime)
                 {
                     //将本人无添加至移除列表
                     mRemoveList.Add(mTaskDict[dkeyList[i]].Id);
                     try
                     {
                         mTaskDict[dkeyList[i]].Run();
                     }
                     catch (Exception e)
                     {
                         DebugUtil.Instance.Log2Time(e, logType.Error);
                     }
                 }
             }
         }
     }
 }