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
Thanks to mike's answer I ended up with:
public static class ExtensionMethods
{
private static readonly ConcurrentDictionary, object> TaskNames = new ConcurrentDictionary, object>();
public static void _Tag(this Task pTask, object pTag)
{
if (pTask == null) return;
var weakReference = ContainsTask(pTask) ?? new WeakReference(pTask);
TaskNames[weakReference] = pTag;
}
public static void _Name(this Task pTask, string name)
{
_Tag(pTask, name);
}
public static object _Tag(this Task pTask)
{
var weakReference = ContainsTask(pTask);
if (weakReference == null) return null;
return TaskNames[weakReference];
}
public static object _Name(this Task pTask)
{
return (string)_Tag(pTask);
}
private static WeakReference ContainsTask(Task pTask)
{
foreach (var kvp in TaskNames.ToList())
{
WeakReference weakReference = kvp.Key;
if (!weakReference.TryGetTarget(out var taskFromReference))
{
TaskNames.TryRemove(weakReference, out _);
//TaskNames.TryRemove(out ); //Keep the dictionary clean.
continue;
}
if (pTask == taskFromReference)
{
return weakReference;
}
}
return null;
}
}
It is thread safe now and it also supports a name not just a tag.