public void Run() { var task = this.GetNextTask(); if (task == null) { return; } this.Log().Info("任务:" + task.GetCode() + "开始执行"); var senderTask = new SenderTask(task); senderTask.onComplete += senderTask_onComplete; this.TaskList.Add(task.GetCode(), senderTask); TaskThread.Post(senderTask); try { this.Log().Info("更新任务状态:" + task.GetCode() + "," + m.TaskStatus.running); taskService.Update(task.GetCode(), (int)m.TaskStatus.running); } catch (Exception ex) { this.Log().Info("更新任务状态异常:" + ex.Message + ex.StackTrace); this.TaskList.Remove(task.GetCode()); } }
public void CloseThread() { if (TaskThread.ThreadState != ThreadState.Aborted) { TaskThread.Abort(); } }
public AppServer() { _mainThread = new TaskThread("执行", MainLoop); _sendThread = new TaskThread("发送", OnSend); _receThread = new TaskThread("接收", OnReceive); Current = this; }
/// <summary> /// 任务暂停 /// </summary> public void Pause() { try { Task.Factory.StartNew(() => { //此功能仅对上传下载有效 if (_Info.Method != Method.Upload && _Info.Method != Method.Download) { return; } _Info.ResultCode = ResultCode.Paused; if (TaskThread != null) { TaskThread.Abort(); TaskThread = null; } else { if (Paused != null) { Paused(this, new FileEventArgs(_Info, null)); } } }); } catch { }; }
/// <summary> /// Shuts down the supervisor. /// </summary> public static void Shutdown() { if (_taskQueue == null) { throw new Exception("TaskManager failed to initialize."); } lock (_taskLock) { lock (_threadsLock) { _threadSLA.Abort(); _threadSLA.Join(); _threadSLA = null; TaskThread[] toStop = new TaskThread[_threads.Count]; _threads.CopyTo(toStop); foreach (TaskThread thread in toStop) { RemoveTaskThread(thread); } } } _stats.MaxThreads.RawValue = 0; ZeroPerformanceCounters(); ShudownPerformanceCounters(); }
void initTaskSchedule() { this.Code = Guid.NewGuid().ToString(); this.Name = _taskSchedule.TaskOperation.Name; this.Description = _taskSchedule.TaskOperation.Description; this._taskThread = new TaskThread(); this._taskThread.Interval = _taskSchedule.TaskOperation.Interval; this._taskThread.IsEnabled = _taskSchedule.TaskOperation.IsEnable; if (_taskSchedule.TaskOperation.FixedTime != null) { this._taskThread.FixedTime = _taskSchedule.TaskOperation.FixedTime.Select(op => new IntervalTime { Day = op.Day, Hour = op.Hour, Minute = op.Minute }).ToList(); } this._taskThread.StopOnErr = _taskSchedule.TaskOperation.StopOnError; this._taskThread.CycleExecutionEvent += (sender, e) => { _taskSchedule.Excute(); //this._taskThread.Dispose(); }; this._taskThread.CycleExecutionExceptionEvent += (sender, e) => { _logger.Log(this.Description + "|监听异常", e.InnerException); _taskSchedule.LisenceException(e.InnerException); }; }
protected void ThreadsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { TaskThread taskThread = e.Item.DataItem as TaskThread; if (taskThread == null) { return; } switch (e.Item.ItemType) { case ListItemType.AlternatingItem: case ListItemType.Item: Label ThreadTitle = e.Item.FindControl("ThreadTitle") as Label; Label Created = e.Item.FindControl("Created") as Label; Label LastStart = e.Item.FindControl("LastStart") as Label; Label LastStop = e.Item.FindControl("LastStop") as Label; Label IsRunning = e.Item.FindControl("IsRunning") as Label; Label Minutes = e.Item.FindControl("Minutes") as Label; ThreadTitle.Text = string.Format("任务线程#{0}统计", threadCount++); Created.Text = taskThread.Created == DateTime.MinValue ? "--" : taskThread.Created.ToString("yyyy/MM/dd HH:mm"); LastStart.Text = taskThread.Started == DateTime.MinValue ? "--" : taskThread.Started.ToString("yyyy/MM/dd HH:mm"); LastStop.Text = taskThread.Completed == DateTime.MinValue ? "--" : taskThread.Completed.ToString("yyyy/MM/dd HH:mm"); IsRunning.Text = taskThread.IsRunning ? "是" : "否"; Minutes.Text = (taskThread.Interval / 60000).ToString() + "分钟"; break; } }
public void Stop() { if (_running) { _running = false; TaskThread.Abort();//之前先释放MessageService的话,进程里仍在使用MessageService会报错,现在改为先释放Thread试试 } }
public void RemoveTask() { Active = false; if (GetRunningStage() != TaskRunStage.Running) { TaskThread.Abort(); EventAfterRun(); } }
/// <summary> /// Finds a task that is ready to be executed. /// </summary> /// <param name="thread">The thread that will execute the task.</param> /// <returns>A task.</returns> /// <remarks>This call might terminate the task execution thread (removing it from the pool) if there are more threads than there are tasks ready to be executed.</remarks> private static TaskWrapper GetScheduledTask(TaskThread thread) { lock (_taskLock) { if (0 == _taskQueue.Count) { return(null); } lock (_threadsLock) { if (_threads.Count(t => !t.IsRunning) > _taskQueue.Count) { RemoveTaskThread(thread); } } for (int i = 0; i < _taskQueue.Count; i++) { TaskWrapper task = _taskQueue.Dequeue(); Thread.MemoryBarrier(); try { DateTime nextAttempt = task.NextAttempt; if (nextAttempt <= DateTime.Now) { double lag = ((double)((TimeSpan)(DateTime.Now - task.NextAttempt)).TotalSeconds) * Stopwatch.Frequency; _stats.AverageLagTime.IncrementBy((long)lag); _stats.BaseAverageLagTime.Increment(); if (task.BurstCounter == 0) { task.BurstStart = DateTime.Now; } _stats.ScheduledTasks.Decrement(); Thread.MemoryBarrier(); return(task); } _taskQueue.Enqueue(task); } catch (AppDomainUnloadedException) { _stats.ScheduledTasks.Decrement(); Thread.MemoryBarrier(); } } return(null); } }
/// <summary> /// Creates Network node /// </summary> /// <param name="type"></param> /// <param name="parallelThreads"></param> /// <param name="solvableProblems"></param> /* public NetworkNode(RegisterType type, TaskThread[] taskThreads) * { * Type = type; * * TaskThreads = taskThreads; * ParallelThreads = (byte)TaskThreads.Count(); * }*/ public NetworkNode(RegisterType type, byte parallelThreads, string[] problems) { Type = type; TaskThreads = new TaskThread[parallelThreads]; for (int i = 0; i < parallelThreads; i++) { TaskThreads[i] = new TaskThread(i, problems[0], messageProcessor, (int)Id); } ParallelThreads = parallelThreads; }
/// <summary> /// Stops an execution thread, removing it from the pool. /// </summary> /// <param name="thread">The task thread.</param> private static void RemoveTaskThread(TaskThread thread) { lock (_threadsLock) { _threads.Remove(thread); _stats.SpawnedThreads.Decrement(); } thread.Stop(); }
/// <summary> /// Called by the execution thread loop to notify the supervisor that it can't find any task ready to be executed. /// </summary> /// <param name="thread">The task thread.</param> private static void NotifyIdleThread(TaskThread thread) { lock (_threadsLock) { if (_threads.Count > 1) { RemoveTaskThread(thread); } } }
internal virtual TaskThread CreateThread(string name, Task[] tasks) { lock (this) { TaskThread thread = new TaskThread(NextName(name), tasks); Threads.Add(thread); thread.Start(); return(thread); } }
public MessageQueue(MessageQueueConfig config, ILog logger, IDictionary <long, PlayerSession> sessionDIc) { _sessionDicRef = sessionDIc; _logger = logger; Port = config.Port; Name = config.Name; AllowedIPs = config.AllowedIPArray.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); _listener = new TcpListener(IPAddress.Any, Port); _thread = new TaskThread(Name, OnReceived); _buffer = new byte[DefaultBufferSize]; }
public MessageQueue(MessageQueueConfig config, ILog logger, IDictionary<long, PlayerSession> sessionDIc) { _sessionDicRef = sessionDIc; _logger = logger; Port = config.Port; Name = config.Name; AllowedIPs = config.AllowedIPArray.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries).ToList(); _listener = new TcpListener(IPAddress.Any, Port); _thread = new TaskThread(Name, OnReceived); _buffer = new byte[DefaultBufferSize]; }
public void Stop() { if (_running) { _running = false; TaskThread.Abort();//之前先释放MessageService的话,进程里仍在使用MessageService会报错,现在改为先释放Thread试试 //SaveThread.Abort(); //MessageService.Dispose(); //MessageService = null; } }
public void Start() { taskThread = new TaskThread(); taskThread.Start(); statusThread = new StatusCheckThread(); statusThread.Start(); sMSSendter = new PinjamSMSSendter(); sMSSendter.Start(); }
public void Dispose() { if (_running) { try { _running = false; TaskThread.Abort(); } catch (Exception) { } } }
protected override void queueEmail(FtdEmail ftdEmail) { //推入Queue中 var dt = new WT_MailQueueDataTable(); var row = dt.newTypedRow(); row.ns_AssignNewId(); serializeMail(row, ftdEmail); dt.addTypedRow(row); dt.ns_update(); TaskThread.taskActive(); }
public static int startNewThread(int memory) { if (SystemInfo.processorCount > activeThreads.Count) { TaskThread newThread = new TaskThread(currentID, memory); newThread.thread.IsBackground = true; newThread.Start(); activeThreads.Add(currentID, newThread); currentID++; return(currentID - 1); } return(-1); }
/// <summary> /// Starts an execution thread, adding it to the pool. /// </summary> private static void SpawnTaskThread() { lock (_threadsLock) { if (_threads.Count < TaskMaxThreads) { TaskThread newThread = new TaskThread(); _threads.Add(newThread); newThread.Start(); _stats.SpawnedThreads.Increment(); } } }
/// <summary> /// Initializes the task manager /// </summary> public void Initialize() { _taskThreads.Clear(); var taskThread = new TaskThread(Run) { Seconds = Interval }; taskThread.InitSeconds = Interval; _taskThreads.Add(taskThread); }
/// <summary> /// Starts the new thread of with given memory amount. /// </summary> /// <returns>The new thread id.</returns> /// <param name="memory">Memory.</param> public static int startNewThread(int memory) { TaskThread newThread = new TaskThread(currentThreadID, memory); newThread.thread.IsBackground = true; newThread.Start(); activeThreads.Add(currentThreadID, newThread); currentThreadID += 1; return(currentThreadID - 1); return(-1); }
public static int loadBalanceTask(Action task) { SimplePriorityQueue <TaskThread> queue = new SimplePriorityQueue <TaskThread> (); foreach (TaskThread thread in activeThreads.Values) { queue.Enqueue(thread, thread.tasks.Count); } TaskThread t = queue.Dequeue(); t.tasks.Enqueue(task); Debug.Log("NEW TASK FOR:" + t.id); return(t.id); }
protected void Start(ITask task) { Debug.Assert(_threads.All(t => t.Thread.IsAlive)); Debug.Assert(_threads.Count <= Math.Min(task.MaxThreads, MaxThreads)); var thread = _threads.FirstOrDefault(t => t.Task == null); if (thread == null) { _threads.Add(thread = new TaskThread(task, this)); } else { thread.Task = task; } }
/* public NetworkNode(RegisterType type, ulong id, uint timeout, string[] problems) * { * Type = type; * * Id = id; * Timeout = timeout; * * TaskThreads = taskThreads; * ParallelThreads = (byte)TaskThreads.Count(); * }*/ /******************************************************************/ /******************* CONSTRUCTORS (SERVER SIDE) *******************/ /******************************************************************/ public NetworkNode(RegisterType type, ulong id, uint timeout, byte parallelThreads, string[] solvableProblems, BackupCommunicationServer[] backupCommunicationServer) { Type = type; Id = id; Timeout = timeout; TaskThread[] taskThreads = new TaskThread[parallelThreads]; for (int i = 0; i < parallelThreads; i++) { taskThreads[i] = new TaskThread((int)id, solvableProblems[0], messageProcessor, (int)Id); } TaskThreads = taskThreads; ParallelThreads = parallelThreads; BackupServers = backupCommunicationServer; SolvableProblems = solvableProblems; }
/// <summary> /// Load balances the task. (Assigns task to thread that is doing the least work) /// </summary> /// <returns>The balanced task.</returns> /// <param name="action">The action to perform.</param> public static Task loadBalanceTask(Action action) { SimplePriorityQueue <TaskThread> queue = new SimplePriorityQueue <TaskThread> (); foreach (TaskThread thread in activeThreads.Values) { queue.Enqueue(thread, thread.tasks.Count); } TaskThread t = queue.Dequeue(); Task task = new Task(action, currentTaskID, t.id); task.debugTask = false; t.tasks.Enqueue(task); currentTaskID += 1; return(task); }
/// <summary> /// 任务取消 /// </summary> public void Cancel() { try { Task.Factory.StartNew(() => { //此功能仅对上传下载有效 if (_Info.Method != Method.Upload && _Info.Method != Method.Download) { return; } _Info.ResultCode = ResultCode.Cancelled; if (TaskThread != null) { TaskThread.Abort(); TaskThread = null; } else { if (_Info.Method == Method.Upload) { Task.Factory.StartNew(() => { FtpHelper.DeleteRemoteFile(_Url + (_Info.NewFilePath == "" ? "" : _Info.NewFilePath + "/") + _Info.NewFileName + ".tmp"); }); FtpHelper.FtpUploadFileInfoList.Remove(_Info); } else { FileHelper.DeleteFile((_Info.NewFilePath == "" ? "" : _Info.NewFilePath + "/") + _Info.NewFileName + ".tmp"); FtpHelper.FtpDownloadFileInfoList.Remove(_Info); } FileHelper.DeleteFile("./Tasks/" + _Info.Method.ToString() + "File/" + _Info.FileNo + ".dat"); if (Cancelled != null) { Cancelled(this, new FileEventArgs(_Info, null)); } } }); } catch { }; }
/// <summary> /// Terminates the task. /// </summary> /// <param name="task">The task.</param> /// <returns>True whether the task was being executed at the time, false otherwise.</returns> private static bool AbortTaskThread(TaskWrapper task) { bool found = false; lock (_threadsLock) { for (int i = _threads.Count - 1; i >= 0; i--) { TaskThread tt = _threads[i]; if (tt.CurrentTask == task) { RemoveTaskThread(tt); _stats.Tasks.Decrement(); found = true; } } SpawnTaskThread(); } return(found); }
public static Task loadBalanceTask(Action action, bool debugTask) { SimplePriorityQueue <TaskThread> queue = new SimplePriorityQueue <TaskThread> (); foreach (TaskThread thread in activeThreads.Values) { queue.Enqueue(thread, thread.tasks.Count); } TaskThread t = queue.Dequeue(); Task task = new Task(action, currentTaskID, t.id); task.debugTask = true; t.tasks.Enqueue(task); if (debugTask) { DLog.Log("NEW TASK " + currentTaskID + " FOR:" + t.id, UnityEngine.Color.yellow); } currentTaskID += 1; return(task); }
/* public NetworkNode(RegisterType type, ulong id, uint timeout, string[] problems) { Type = type; Id = id; Timeout = timeout; TaskThreads = taskThreads; ParallelThreads = (byte)TaskThreads.Count(); }*/ /******************************************************************/ /******************* CONSTRUCTORS (SERVER SIDE) *******************/ /******************************************************************/ public NetworkNode(RegisterType type, ulong id, uint timeout, byte parallelThreads, string[] solvableProblems, BackupCommunicationServer[] backupCommunicationServer) { Type = type; Id = id; Timeout = timeout; TaskThread[] taskThreads = new TaskThread[parallelThreads]; for (int i = 0; i < parallelThreads; i++) { taskThreads[i] = new TaskThread((int)id, solvableProblems[0], messageProcessor,(int)Id); } TaskThreads = taskThreads; ParallelThreads = parallelThreads; BackupServers = backupCommunicationServer; SolvableProblems = solvableProblems; }
/// <summary> /// Finds a task that is ready to be executed. /// </summary> /// <param name="thread">The thread that will execute the task.</param> /// <returns>A task.</returns> /// <remarks>This call might terminate the task execution thread (removing it from the pool) if there are more threads than there are tasks ready to be executed.</remarks> private static TaskWrapper GetScheduledTask(TaskThread thread) { lock (_taskLock) { if (0 == _taskQueue.Count) { return null; } lock (_threadsLock) { if (_threads.Count(t => !t.IsRunning) > _taskQueue.Count) { RemoveTaskThread(thread); } } for (int i = 0; i < _taskQueue.Count; i++) { TaskWrapper task = _taskQueue.Dequeue(); Thread.MemoryBarrier(); try { DateTime nextAttempt = task.NextAttempt; if (nextAttempt <= DateTime.Now) { double lag = ((double)((TimeSpan)(DateTime.Now - task.NextAttempt)).TotalSeconds) * Stopwatch.Frequency; _stats.AverageLagTime.IncrementBy((long)lag); _stats.BaseAverageLagTime.Increment(); if (task.BurstCounter == 0) { task.BurstStart = DateTime.Now; } _stats.ScheduledTasks.Decrement(); Thread.MemoryBarrier(); return task; } _taskQueue.Enqueue(task); } catch (AppDomainUnloadedException) { _stats.ScheduledTasks.Decrement(); Thread.MemoryBarrier(); } } return null; } }
/// <summary> /// Creates Network node /// </summary> /// <param name="type"></param> /// <param name="parallelThreads"></param> /// <param name="solvableProblems"></param> /* public NetworkNode(RegisterType type, TaskThread[] taskThreads) { Type = type; TaskThreads = taskThreads; ParallelThreads = (byte)TaskThreads.Count(); }*/ public NetworkNode(RegisterType type, byte parallelThreads, string[] problems) { Type = type; TaskThreads = new TaskThread[parallelThreads]; for (int i = 0; i < parallelThreads; i++) { TaskThreads[i] = new TaskThread(i, problems[0], messageProcessor,(int)Id); } ParallelThreads = parallelThreads; }
/*******************************************************************/ /************************* PUBLIC METHODS **************************/ /*******************************************************************/ /// <summary> /// Adds a thread to the network node /// </summary> /// <param name="taskThread"></param> public void AddThread(TaskThread taskThread) { // TODO }