Is it okay to use Task
as dictionary key or is that a bad idea? Any problems which might occur because of that?
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");