监控任务 [英] Monitoring Tasks

查看:51
本文介绍了监控任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以问题是我有一个 ThreadManager 类,该类使用队列保存 Task 对象; ThreadManager 可以通过调用 Task Start()方法来启动 Task ,该方法将从中生成线程运行某种算法(实际的任务").现在,我要实现的是让 ThreadManager 监视任务线程的状态(由 Task Start()方法生成)>对象).

So the problem is I have a ThreadManager class which use queue to hold the Task objects; the ThreadManager can start the Task by invoking the Task's Start() method from which will generate a thread to run some algorithm (the actual "task"). Now what I want to achieve is to let the ThreadManager to monitor the status of the task thread (generated from the Start() method of the Task object).

为此,我想我需要创建一个线程在 ThreadManager 中进行监视,并且我需要一种让任务线程触发事件以通知监视线程的方法我已经完成,或者遇到了一些错误,因此监视器可以相应地处理这些事件.

For this to work, I think I need to create a thread to do the monitoring in the ThreadManager, and I need a way to let the task thread to fire events to notify the monitor thread that I am finished or I encountered some error, so the monitor can handle these event accordingly.

大师,请问我是否适用我的想法?如果是的话,如何实现此工作流程?非常感谢!

Gurus, please advise me if my idea is applicable? And if it is, how to achieve this workflow? Many thanks!

推荐答案

我只会使用 Task.ContinueWith 为每个任务安排一个延续,然后根据的结果更改状态您继续执行的任务.您知道任务已经启动(因为您调用了 Start())-您只需要知道任务何时完成即可.如果失败,取消或完成,则可以在继续任务中观察到该情况,然后可以更新状态.继续任务是 Action< Task> ,它接收已完成的任务.您可以调用 task.Status 来获取已完成任务的状态.

I would just use Task.ContinueWith to schedule a continuation for each of the tasks and then change the status depending on the result of the task in your continuation. You know that the task has been started (because you called Start()) - you just need to know when the task completes. If it fails, is cancelled, or finishes, you can observe that in the continuation task and then you can update your status. The continuation task is an Action<Task>, which receives the completed task. You can call task.Status to get the status of that completed task.

然后,您不需要单独的线程/任务即可定期监视状态.

Then you don't need to have a separate thread/task to monitor the status periodically.

这篇关于监控任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆