C# get object from asyncron task

122 Views Asked by At

i just startet thread programming in c#. And I realy dont know if this is the right community to ask questions like that. If not, im sorry.

I have two functions, start() and status(). In start() I create an new task like:

start() {
   for each(dir => ListOfAllDirs) {
       new Task(() => { yr.LoadAllFiles(dir); }).Start();
   }
 }

so I have about 200 parallel Tasks Running with this code:

class yr
{
    List<Values> rv = new List<Values>();
    public List<Values> LoadAllFiles(string dir)
    {
       [...DoStuff...]
       rv.Add(...);
       rv.Add(...);
       rv.Add(...);
    }

}

So I dont know how to access the > 200 running Threads to get the data, before they're finished. I'm looking for sth. like:

status(dir) {
    int count = GetTaskByName[dir].rv.Count; (????)
    Console.WriteLine("Dir " + dir + "->" + count + "files checked");
}

And the final Output:

Dir AA -> 19 files checkes
Dir AB -> 12 files checkes
Dir BB -> 49 files checkes
Dir AA -> 29 files checkes

So to be clear: 200 dirs, 200 tasks, everything is running asyncron. How do I access a specific Task / get Data from the running Task.

2

There are 2 best solutions below

2
On BEST ANSWER

Apparently, you need to take 200 directories and compute a result for each of them. PLINQ makes that exceptionally easy:

var results =
ListOfAllDirs
.AsParallel()
.Select(dir => new { dir, result = yr.LoadAllFiles(dir) })
.ToList();

And there's your list of directories plus the computation result.

You can do it manually with tasks as well. In that case you probably want a sequence like this:

  1. Create all tasks and store them
  2. Use Task.WaitAll to wait for completion
  3. Use Task.Result on each task to get the result
0
On

Are you looking for something like this?

var task = Task<List<values>>.Run((() => { return yr.LoadAllFiles(dir);}));
List<values> result = task.Result;

If it has a result type, you access the result on the task. That waits for the task to complete and gets the result.