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