visit
public static void BasicParallelForLoop()
{
long totalSize = 0;
Console.WriteLine("Enter valid directory path :");
String args = Console.ReadLine();
if (!Directory.Exists(args))
{
Console.WriteLine("The specified directory does not exist.");
return;
}
String[] files = Directory.GetFiles(args);
Parallel.For(0, files.Length,
index =>
{
FileInfo fileInfo = new FileInfo(files[index]);
long size = fileInfo.Length;
Interlocked.Add(ref totalSize, size);
});
Console.WriteLine("Directory '{0}':, {1:N0} files, {2:N0} bytes", args, files.Length, totalSize);
}
//Valid directory scenario
Enter valid directory path :
E:\gifs
//Result
Directory 'E:\gifs':, 7 files, 2,313,294 bytes
//Invalid directory Result
//The specified directory does not exist.
Example Reference
Let’s consider an example of iterating a directory and output the following things:
- The number of files inside the directory, not subfolder files though.
- Size in bytes
Let's write some code. Notice the syntax is much more readable as the file object is directly managed rather than indexed.
String[] files = Directory.GetFiles(args);
Parallel.ForEach(files, (currentFile) =>
{
FileInfo fileInfo = new FileInfo(currentFile);
long size = fileInfo.Length;
Interlocked.Add(ref totalSize, size);
});
Console.WriteLine("Directory '{0}':, {1:N0} files, {2:N0} bytes", args, files.Length, totalSize);
//Valid directory scenario
Enter valid directory path :
E:\gifs
//Result
Directory 'E:\gifs':, 7 files, 2,313,294 bytes
//Invalid directory Result
//The specified directory does not exist.
Let's write some code.
Use the "ParallelOptions" class object to provide a cancellation token and max parallelism. Notice that the code below shows a "Task Creation" using "Task.Factory", so we can cancel from another thread. The example below demonstrates how to apply the cancellation token on "For Loop," Likewise, it can be used for "ForEach Loop" as well.
public static void BasicCancelLoop()
{
int[] nums = Enumerable.Range(0, 100000000).ToArray();
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.CancellationToken = cts.Token;
parallelOptions.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
Console.WriteLine("Press any key to start. Press 's' to cancel.");
Console.ReadKey();
Task.Factory.StartNew(() =>
{
if (Console.ReadKey().KeyChar == 's')
cts.Cancel();
Console.WriteLine("press any key to exit");
});
try
{
Parallel.ForEach(nums, parallelOptions, (num) =>
{
Console.WriteLine("{0} on {1}", num);
parallelOptions.CancellationToken.ThrowIfCancellationRequested();
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
}
}
//print num values
....
....
....
//s key pressed
The operation was cancelled
Exception Handling Code
public static void Handle()
{
int[] data = new int[3] { 1, 2, 3 };
try
{
ProcessDataInParallel(data);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
}
}
private static void ProcessDataInParallel(int[] data)
{
Parallel.ForEach(data, d =>
{
throw new ArgumentException($"Exception with value : {d}");
});
}
One or more errors occurred. (Exception with value 1) (Exception with value 3) (Exception with value 2)
//github.com/ssukhpinder/TaskParallelLibExample