How can I assign a name to a task in TPL

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

    If you only need to know the name of the task after the task is finished then you could just pass it as a parameter. Return it as a part of the task result.

        private async Task MyTask(int x, string taskName)
        {
            return new[]
            {
                taskName, x.ToString()
            };
        }
    

    Or map your tasks to a dictionary

            var mapping = new Dictionary();
            var task = new Task(() => Console.WriteLine("myNullTask"));
            mapping.Add(task, "myNullTask");
            foreach (var taskX in mapping)
            {
                Console.WriteLine(
                    $"Task Id: {taskX.Key.Id}, " +
                    $"Task Name: {taskX.Value}, " +
                    $"Task Status: {taskX.Key.Status}");
            }
    

提交回复
热议问题