Warm tip: This article is reproduced from stackoverflow.com, please click
c# dictionary task task-parallel-library

Use Task as dictionary key?

发布于 2020-04-23 10:09:14

Is it okay to use Task as dictionary key or is that a bad idea? Any problems which might occur because of that?

Questioner
Grigoryants Artem
Viewed
41
Alexei Levenkov 2020-02-06 14:49

Tasks don't have they own GetHashCode and are reference types derived directly from Object. As result GetHashCode/Equals does not vary based on state of the object and just depend on object's reference (GetHashCode).

As result Task can be used as key for dictionary and will allow to do fast lookup from a task to data. The matches will be on exact objects.

Common usage - associate some data with running tasks by code that runs them, i.e. logging ID:

 Task task1 = Task.Delay(100);
 Task[] allTasks = new[]{task1}; 

 var dictionary = new Dictionary<Task, string> { {task1, "first-task"}};

 Task completed = await Task.WhenAny(allTasks);
 Console.WriteLine($"Task {dictionary[completed]} finished");