C # get object from asyncron task
I am just getting started with thread programming in C #. And I really don't know if this community is right to ask such questions. If not, they're sorry.
I have two functions: start () and status (). In start () I create a new task, for example:
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 don't know how to access> 200 running threads to get the data before it runs out. I'm looking for sth. as:
status(dir) {
int count = GetTaskByName[dir].rv.Count; (????)
Console.WriteLine("Dir " + dir + "->" + count + "files checked");
}
And the final conclusion:
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 works asyncron. How to access a specific Task / Get data from a running task.
source to share
Apparently you need to take 200 directories and calculate the result for each one. PLINQ makes this extremely simple:
var results =
ListOfAllDirs
.AsParallel()
.Select(dir => new { dir, result = yr.LoadAllFiles(dir) })
.ToList();
And here is a list of directories and the result of calculations.
You can do it manually and with tasks. In this case, you probably need a sequence like this:
- Create all tasks and save them
- Use Task.WaitAll to wait for completion
- Use Task.Result for each task to get the result
source to share