How can I assign a name to a task in TPL

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

    I thought of having a dictionary to aid debugging, etc.

    Here's a sample of what I have been doing:

    private static void Main(string[] args)
    {
        var tasksIdDic = new ConcurrentDictionary();
        Random rnd = new Random(DateTime.Now.Millisecond);
        var tasks = new List();
    
        tasks.Add(Task.Run(() =>  
        {
            Task.Delay(TimeSpan.FromSeconds(rnd.Next(1, 5))).Wait();
            tasksIdDic.TryAdd(Task.CurrentId, "First");
    
            Console.WriteLine($"{tasksIdDic[Task.CurrentId]} completed.");
        }));
    
        tasks.Add(Task.Run(() =>
        {
            Task.Delay(TimeSpan.FromSeconds(rnd.Next(1, 5))).Wait();
            tasksIdDic.TryAdd(Task.CurrentId, "Second");
    
            Console.WriteLine($"{tasksIdDic[Task.CurrentId]} completed.");
        }));
    
        tasks.Add(Task.Run(() =>
        {
            Task.Delay(TimeSpan.FromSeconds(rnd.Next(1, 5))).Wait();
            tasksIdDic.TryAdd(Task.CurrentId, "Third");
    
            Console.WriteLine($"{tasksIdDic[Task.CurrentId]} completed.");
        }));
    
       //do some work - there is no guarantee, but assuming you add the task names to the dictionary at the very beginning of each thread, the dictionary will be populated and be of benefit sometime soon after the start of the tasks.
       //Task.Delay(TimeSpan.FromSeconds(5)).Wait();
    
        //wait for all just so I see a console output
        Task.WaitAll(tasks.ToArray());
    }
    

提交回复
热议问题