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;
}
这是我从一本书中得到的一段代码。我对此有疑问。
变量tasklocaltotal
将处于线程级别或任务级别。根据本书,它处于任务级别,但由于线程可以执行多个任务,因此变量在整个程序执行过程中保持其值的方式。
我认为它应该在线程级别。
有人可以提供有关此内容的见解以及可能的更多链接,以便我可以更清楚地了解这一概念。