Hey guys, I am playing with the .NET 4.0's new class Parallel.
I tried to open files in a directory and calculate the total bytes of them. However when I run the code, I get a different result every time.
Can you explain me the problem I have?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
using System.IO;
using System.Drawing;
namespace LearnCSharp
{
class Program
{
static long totalBytes = 0;
private static object token = new object();
static void ProcessImages()
{
string directoryPath = @"C:\files";
string[] fileNames = Directory.GetFiles(directoryPath);
if (fileNames == null)
throw new Exception("Path is wrong");
ParallelLoopResult result = Parallel.ForEach<string>(fileNames, new Action<string>(
delegate(string fileName)
{
FileStream stream = File.OpenRead(fileName);
if (stream == null)
throw new Exception("File not found");
lock (token)
{
totalBytes =+ stream.Length;
}
}
));
}
static void Main(string[] args)
{
TaskFactory taskFactory = new TaskFactory();
Task task = taskFactory.StartNew(new Action(ProcessImages));
Task.WaitAll(task);
Console.WriteLine(totalBytes);
Console.Read();
}
}
}