How can I assign a name to a task in TPL

后端 未结 11 1263
礼貌的吻别
礼貌的吻别 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:28

    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;
        }
    }
    

提交回复
热议问题