0

I had thread arrays in my code which I am going to replace with task.

 Dictionary<string, name> threadnames = new Dictionary<string, name>();
 public Thread [] Threads;
 string[] nodeKeys;

 for (int i = 0; i < nodeKeys.Length; i++)
 {
   Threads[i] = new Thread(() => ThreadMethod(nodeKey));
   Threads[i].Name = nodeKey[i];
   names.Add(Threads[i].Name, null);
   Threads[i].Start();
 }

This was the old approach in which I was also saving my thread names in a separate dictionary. Now I am going to convert it to task what so far I have done is this

 Dictionary<string, name> threadnames = new Dictionary<string, name>();
 string[] nodeKeys;

 for (int i = 0; i < nodeKeys.Length; i++)
 {
  var runningTask = new Task(() => ThreadMethod(nodeKey[i]));
  runningTask.Start();
 }

Now since all is in for loop, should all of this be done in single task? Or if the above is right approach what about the task id I have to get?

Or if there is better approach to do it will be appreciated.

2
  • If you need to keep track of the tasks, why don't you simply add them to a List<Task>? Why do you need a name or an id? Commented Apr 1, 2019 at 11:54
  • Thats because i have to keep its track in separate dictionary . Commented Apr 1, 2019 at 12:36

1 Answer 1

1

A Task has no concept of a name. But since you seem to create a Task per string in your nodeKeys array, you could use this string as the key provided that it is unique:

Dictionary<string, Task> tasks = new Dictionary<string, Task>();
string[] nodeKeys;

for (int i = 0; i<nodeKeys.Length; i++)
{
    tasks[nodeKey[i]] = Task.Run(() => ThreadMethod(nodeKey[i]));
}

Another option may to just add the tasks as-is, without any identifier, to a List<Task> or a Task[]:

List<Task> tasks = new List<Task>();
string[] nodeKeys;

for (int i = 0; i<nodeKeys.Length; i++)
{
    tasks.Add(Task.Run(() => ThreadMethod(nodeKey[i])));
}

You may await an array of tasks using the Task.WhenAll method:

await Task.WhenAll(tasks.ToArray());
//or await Task.WhenAll(tasks.Values.ToArray());
Sign up to request clarification or add additional context in comments.

1 Comment

I would think you'd have to copy the loop variable before the capture.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.