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;
}
}
You could relate any object with any object. Here is an extension for Task. It uses a WeakReference so the task can still be garbage collected when all references are out of scope.
Usage:
var myTask = new Task(...
myTask.Tag("The name here");
var nameOfTask = (string)myTask.Tag();
Extension class:
public static class TaskExtensions
{
private static readonly Dictionary<WeakReference<Task>, object> TaskNames = new Dictionary<WeakReference<Task>, object>();
public static void Tag(this Task pTask, object pTag)
{
if (pTask == null) return;
var weakReference = ContainsTask(pTask);
if (weakReference == null)
{
weakReference = new WeakReference<Task>(pTask);
}
TaskNames[weakReference] = pTag;
}
public static object Tag(this Task pTask)
{
var weakReference = ContainsTask(pTask);
if (weakReference == null) return null;
return TaskNames[weakReference];
}
private static WeakReference<Task> ContainsTask(Task pTask)
{
foreach (var kvp in TaskNames.ToList())
{
var weakReference = kvp.Key;
Task taskFromReference;
if (!weakReference.TryGetTarget(out taskFromReference))
{
TaskNames.Remove(weakReference); //Keep the dictionary clean.
continue;
}
if (pTask == taskFromReference)
{
return weakReference;
}
}
return null;
}
}