For beginners we can use multithreading concepts for parallel processing
--Simple console application in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<string> files = new List<string>();
Console.WriteLine("Please provide the directory you would like to count:");
string root = Console.ReadLine();
Console.WriteLine("Counting files .....");
GetAllFilesWithParallel(root, (f) => { files.Add(f); });
if (files.Count != 0)
Console.WriteLine(string.Format("Total files in {0}", files.Count()));
// Keep the console window open.
Console.ReadKey();
}
public static List<string> GetAllFilesWithParallel(string root, Action<string> action)
{
//generic list for holding all the files
List<string> list = new List<string>();
//Count of files traversed
int i = 0;
//stack to hold all the file names
Stack<string> dirs = new Stack<string>();
try
{
//first make sure the directory provided actually exists
if (!System.IO.Directory.Exists(root))
{
Console.WriteLine(string.Format("The specified directory {0} could not be found", root));
return null;
}
//insert the root directory onto our stack (for later use)
dirs.Push(root);
//now we start looping
while (dirs.Count > 0)
{
//variables needed for this task
string currentDirectory = dirs.Pop();
string[] subDirectories = null;
string[] files = null;
//first get the subdirectories in the specified directory
subDirectories = System.IO.Directory.GetDirectories(currentDirectory);
//now get all the files in the current directory
files = System.IO.Directory.GetFiles(currentDirectory);
//add all the subdirectories onto the stack for traversal
foreach (string str in subDirectories)
dirs.Push(str);
//now use the Parallel.ForEach loop to get all the files in the current directory
//and add them to our generic list
Parallel.ForEach(files, () => 0, (file, loopState, localCount) =>
{
action(file);
return (int)++localCount;
},
(c) =>
{
Interlocked.Exchange(ref i, i + c);
});
}
}
catch (AggregateException e)
{
e.Handle((ex) =>
{
if (ex is UnauthorizedAccessException)
{
// Here we just output a message and go on.
Console.WriteLine(ex.Message);
return true;
}
return false;
});
}
return list;
}
}
}
Reference:
http://dotnet.dzone.com/articles/c-40-begginers-look-parallel
For WPF application with parallel programming refer
http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
NOTE: Refer this link for E-Book
http://it-ebooks.info/book/1527/ Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif
krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator