private static Int64 DirectoryBytes(String path)
{
var files = Directory.EnumerateFiles(path);
Int64 masterTotal = 0;
ParallelLoopResult result = Parallel.ForEach<String, Int64>(
files,
() =>
{ // localInit: Invoked once per task at start
// Initialize that this task has seen 0 bytes
return 0; // Set taskLocalTotal initial value to 0
},
(file, loopState, index, taskLocalTotal) =>
{ // body: Invoked once per work item
// Get this file's size and add it to this task's running total
Int64 fileLength = 0;
FileStream fs = null;
try
{
fs = File.OpenRead(file);
fileLength = fs.Length;
}
catch (IOException) { /* Ignore any files we can't access */ }
finally { if (fs != null) fs.Dispose(); }
return taskLocalTotal + fileLength;
},
taskLocalTotal =>
{ // localFinally: Invoked once per task at end
// Atomically add this task's total to the "master" total
Interlocked.Add(ref masterTotal, taskLocalTotal);
});
return masterTotal;
}
This is a piece of code I got from a book. I have a doubt in this.
The variable tasklocaltotal will be at a thread level or a task level. As per the book it is at task level, but since multiple tasks can be executed by a thread than how come the variable is maintaining its value throughout the execution of the program.
I think it should be at the thread level.
Can someone provide insight on this and possible more links to read where I can get this concept more clear.
The overload of ForEach that is being used here specifies that the last parameter is an Action that is called for each ended task.
So at the end of each task the task’s result is passed to the Interlocked.Add method which increments the masterTotal with that task’s local total.
The confusing part is this part:
Just think of it as (you can even write it as):
taskLocalTotal unfortunately has the same name here as in the Task’s action.
So it is not the same variable but just the same name.