有没有办法判断任务并行库中当前正在运行哪些任务? [英] Is there a way to tell which Tasks are currently running in Task Parallel Library?

查看:23
本文介绍了有没有办法判断任务并行库中当前正在运行哪些任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不到查看哪些任务正在运行的方法.有 Task.Current 属性,但是如果有多个任务在运行呢?有没有办法获得这种信息?

I can't see a way to see which tasks are running. There is the Task.Current property, but what if there are multiple tasks running? Is there a way to get this kind of information?

或者,是否有一种内置方式可以在任务开始或完成时获得通知?

Alternately, is there a built in way to get notified when a task starts or completes?

推荐答案

嘿 Mike,在 TPL 中没有访问待处理任务列表的公共方式.使其可用于调试器的机制依赖于所有线程将在枚举时被冻结的事实,因此它不能在运行时使用.

Hey Mike, there is no public way of accessing the list of pending tasks in TPL. The mechanism that makes it available for the debugger relies on the fact that all threads will be frozen at enumeration time, therefore it can't be used at runtime.

是的,有一种内置方式可以在任务完成时收到通知.查看 Task.ContinueWith API.基本上这个 API 创建了一个新任务,当目标任务完成时它会被触发.

Yes, there's a built in way to get notified whan a task completes. Check out the Task.ContinueWith APIs. Basically this API creates a new task that will fired up when the target task completes.

我假设您想基于此进行一些快速会计/进度报告,如果是这种情况,我建议您使用 TaskContinuationOptions.ExecuteSynchronously 标志调用 task.ContinueWith().当您指定在目标任务完成时继续操作将在同一线程上运行时(如果您不指定此项,则继续任务将像任何其他常规任务一样排队).

I'm assuming you want to do some quick accounting / progress reporting based on this, if that's the case, I'd recommend that you call task.ContinueWith() with the TaskContinuationOptions.ExecuteSynchronously flag. When you specify that the continuation action will be run right there on the same thread when the target task finishes (if you don't specify this the continuation task is queued up like any other regular task).

希望这会有所帮助.

侯赛因

这篇关于有没有办法判断任务并行库中当前正在运行哪些任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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