Monitoring Tasks
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).
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!
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.
I think you can use the Task.IsCompleted property on each of the Task objects you may have in your manager collection. Hope this is what your asking?
精彩评论