How can I assign a name to a task in TPL

后端 未结 11 1265
礼貌的吻别
礼貌的吻别 2021-02-12 10:24

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

11条回答
  •  迷失自我
    2021-02-12 11:11

    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.

提交回复
热议问题