问题描述
我将使用在我的应用程序上运行的许多任务.由于某些原因,每堆任务都在运行.我想为这些任务命名,以便当我看到并行任务"窗口时,可以轻松识别它们.
I'm going to use lots of tasks running on my application. Each bunch of tasks is running for some reason. I would like to name these tasks so when I watch the Parallel Tasks window, I could recognize them easily.
从另一个角度来看,请考虑我在框架级别使用任务来填充列表.使用我的框架的开发人员也在使用任务进行工作.如果她查看并行任务"窗口,则会发现一些不知道的任务.我想给任务命名,以便她可以区分框架任务和任务.
With another point of view, consider I'm using tasks at the framework level to populate a list. A developer that use my framework is also using tasks for her job. If she looks at the Parallel Tasks Window she will find some tasks having no idea about. I want to name tasks so she can distinguish the framework tasks from her tasks.
如果有这样的API,将非常方便:
It would be very convenient if there was such API:
var task = new Task(action, "Growth calculation task")
或者也许:
var task = Task.Factory.StartNew(action, "Populating the datagrid")
,甚至在使用 Parallel.ForEach
Parallel.ForEach(list, action, "Salary Calculation Task"
可以命名任务吗?
是否可以给 Parallel.ForEach
一个命名结构(也许使用lambda),以便它使用该命名来创建任务?
Is it possible to give Parallel.ForEach
a naming structure (maybe using a lambda) so it creates tasks with that naming?
我缺少某个地方的API吗?
Is there such API somewhere that I'm missing?
我还尝试过使用继承的任务来覆盖它的ToString().但是不幸的是,并行任务"窗口未使用ToString()!
I've also tried to use an inherited task to override it's ToString(). But unfortunately the Parallel Tasks window doesn't use ToString()!
class NamedTask : Task
{
private string TaskName { get; set; }
public NamedTask(Action action, string taskName):base(action)
{
TaskName = taskName;
}
public override string ToString()
{
return TaskName;
}
}
推荐答案
您不能真正命名 Task
,但是可以命名由 Task执行的方法代码>,然后在并行任务"窗口中显示.因此,如果命名
Task
对您来说很重要,请不要使用lambda,而应使用常规的命名方法.
You can't really name a Task
, but you can name the method which is executed by a Task
, which is then shown in the Parallel Tasks windows. So, if naming the Task
s is important for you, don't use lambdas, use normal named methods.
令人惊讶的是,即使 Task
并没有直接执行您的方法,这也适用于 Parallel
.我认为这是因为并行任务以某种方式从 Parallel
了解了 Task
s并以不同的方式处理它们.
Surprisingly, this works even with Parallel
, even though there the Task
isn't executing your method directly. I think this is because Parallel Tasks somehow knows about Task
s from Parallel
and handles them differently.
这篇关于如何在TPL中为任务分配名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!