简体   繁体   English

监控任务

[英]Monitoring Tasks

So the problem is I have a ThreadManager class which use queue to hold the Task objects; 所以问题是我有一个ThreadManager类,该类使用队列来保存Task对象。 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"). ThreadManager可以通过调用TaskStart()方法来启动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监视任务线程的状态(从Task对象的Start()方法生成)。

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. 为此,我想我需要创建一个线程在ThreadManager进行监视,并且我需要一种方法让任务线程触发事件以通知监视线程我已完成或遇到一些错误,因此监视器可以相应地处理这些事件。

Gurus, please advise me if my idea is applicable? 大师,请告诉我我的想法是否适用? And if it is, how to achieve this workflow? 如果是的话,如何实现此工作流程? Many thanks! 非常感谢!

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. 我只是使用Task.ContinueWith来安排每个任务的继续,然后根据继续中任务的结果更改状态。 You know that the task has been started (because you called Start() ) - you just need to know when the task completes. 您知道任务已经启动(因为您调用了Start() )-您只需要知道任务何时完成即可。 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. 继续任务是Action<Task> ,它接收已完成的任务。 You can call task.Status to get the status of that completed task. 您可以调用task.Status来获取该已完成任务的状态。

Then you don't need to have a separate thread/task to monitor the status periodically. 然后,您不需要单独的线程/任务即可定期监视状态。

I think you can use the Task.IsCompleted property on each of the Task objects you may have in your manager collection. 我认为您可以在管理器集合中可能具有的每个Task对象上使用Task.IsCompleted属性。 Hope this is what your asking? 希望这是您的要求?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM