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 wi
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, object> TaskNames = new Dictionary, object>();
public static void Tag(this Task pTask, object pTag)
{
if (pTask == null) return;
var weakReference = ContainsTask(pTask);
if (weakReference == null)
{
weakReference = new WeakReference(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 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;
}
}