How can I assign a name to a task in TPL

Posted by mehrandvd on Stack Overflow See other posts from Stack Overflow or by mehrandvd
Published on 2012-12-07T11:34:54Z Indexed on 2012/12/09 17:04 UTC
Read the original article Hit count: 238

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.

It would be very convenient if there was such API:

var task = new Task(action, "Growth calculation task")

or maybe:

var task = Task.Factory.StartNew(action, "Populating the datagrid")

or even while working with Parallel.ForEach

Parallel.ForEach(list, action, "Salary Calculation Task"

Is it possible to name a task?

Is it possible to give ???Parallel.ForEach a naming structure (maybe using a lambda) so it creates tasks with that naming?

Is there such API somewhere that I'm missing?


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;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about task-parallel-library