How can I assign a name to a task in TPL
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;
}
}
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.
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.
You can't name tasks.
The task library is internally using a thread pool, so the threads can't be named. Also your inheritance approach won't work, because methods like ".ContinueWith()" will always create a new task, which won't inherit from your class.