How can I assign a name to a task in TPL

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

    In case this is helpful for anyone, I addressed the above issue as follows:

    public static class NamedTasks
    {
        public static Dictionary ActiveTasks { get; private set; } = new Dictionary();
    
        public static void Run(string name, Action action)
        {
            var task = new Task(action);
            ActiveTasks.Add(name, task);
            task.Start();
    
        public static void RemoveTask(string name)
        {
            if (ActiveTasks.ContainsKey(name))
                ActiveTasks.Remove(name);
        }
    }
    

    Usage:

    // Start new named task
    var taskName = " - ";
    NamedTasks.Run(taskName, () =>
    {
        // do stuff
        NamedTasks.RemoveTask(taskName);
    });
    
    ...
    
    // Print names of active tasks
    var taskNames = NamedTasks.ActiveTasks.Keys.ToList();
    foreach (var taskName in taskNames)
        if (NamedTasks.ActiveTasks[taskName].Status == TaskStatus.Running)
            Console.WriteLine(taskName);
    

    This worked quite nicely for me.

提交回复
热议问题