There days almost all computers are assembled with multicore processors, and the time is different from when you had simple single core processor processing single instruction at a time of your program. If you creating an application that has to be installed on multicore CPU machine, then application should be able to utilize as CPUs as it can to give the performance. But to develop such application you need to be quite skilled in multhithreaded programming techniques
With the .Net 4.0, you are provided with the brand new parallel programming language library called as TPL “Task Parallel Library”. Using the classes in System.Threading.Tasks namespace, you can build fine grained, scalable parallel code without having to work directly with threads.
The Task Parallel Library API
The primary class of the TPL is System.Threading.Tasks.Parallel. This class provides you a number of methods which allows you to iterate over a collection of data, (specifically which implements the IEnumerable<T>) in a parallel fashion. Main two static methods of this classes are Parallel.For() and Parallel.Foreach(), each of which defines numerous overloaded versions.
Lets create an small search application in WindowsForms:
Create a simple form like below.
Now click of Search Button write the code below:
- string path = "H:\\";
- private void btnSearch_Click(object sender, EventArgs e)
- {
- DateTime startTime = DateTime.Now;
- DateTime endTime;
- string[] dirs = Directory.GetDirectories(path);
- List<string> lstFiles = new List<string>();
- foreach (string dir in dirs)
- {
- this.Text = "Searching " + dir;
- try
- {
- lstFiles.AddRange(Directory.GetFiles(dir, "*.doc*", SearchOption.AllDirectories));
- }
- catch (Exception ex)
- {
- continue;
- }
- }
- endTime = DateTime.Now;
- TimeSpan ts = endTime.Subtract(startTime);
- MessageBox.Show("Search Complete!! \n Time elapsed:" + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds);
- }
OUTPUT:
Now write the same logic using the Parallel.ForEach() function of System.Threading.Tasks
- private void btnSearch_Click(object sender, EventArgs e)
- {
- DateTime startTime = DateTime.Now;
- DateTime endTime;
- string[] dirs = Directory.GetDirectories(path);
- List<string> lstFiles = new List<string>();
- Parallel.ForEach(dirs, dir =>
- {
- try
- {
- lstFiles.AddRange(Directory.GetFiles(dir, "*.doc*", SearchOption.AllDirectories));
- }
- catch
- {
- // do nothing
- }
- });
- endTime = DateTime.Now;
- TimeSpan ts = endTime.Subtract(startTime);
- MessageBox.Show("Search Complete!! \nFiles Found:" + lstFiles.Count + "\n Time elapsed:" + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds);
- }
OUPUT:
Little faster than the Previous one!
But here you must be facing a problem. Have you tried writing something during this operation on the UI. I don’t if you could do that cause UI was freezing because Main thread is waiting for the operation to complete that is executing in Synchronous manner.
Let use few more Powerful functionality of System.Threading.Tasks to make the UI interactive while work is being done.
Place all the code inside the a function say SearchDirectory().
- private void SearchDirectory()
- {
- DateTime startTime = DateTime.Now;
- DateTime endTime;
- string[] dirs = Directory.GetDirectories(path);
- List<string> lstFiles = new List<string>();
- Parallel.ForEach(dirs, dir =>
- {
- try
- {
- lstFiles.AddRange(Directory.GetFiles(dir, "*.doc*", SearchOption.AllDirectories));
- }
- catch
- {
- // do nothing
- }
- });
- endTime = DateTime.Now;
- TimeSpan ts = endTime.Subtract(startTime);
- MessageBox.Show("Search Complete!! \nFiles Found:" + lstFiles.Count + "\n Time elapsed:" + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds);
- }
- private void btnSearch_Click(object sender, EventArgs e)
- {
- //Start a task to process a file
- Task.Factory.StartNew(() => SearchDirectory());
- }
The Factory property of Task Class returns TaskFactory object. When you call its StartNew() method, you pass in an Action<T> delegate (Here lambda expression is hiding the expression). Now your UI will be able to receive input and will not block.
Note: I changed the search path from drive h:\ to c:\ so that i could get time write something thats why the time here is little different than the earlier output.
OUTPUT:
Including Cancellation Reqeust for background process:
The Parallel.Foreach() and Paralled.For() both support the cancellation through the Cancellation tokens. When you invoke the methods on Parallel, you can pass in a ParallelOptions object, which in turn contains a CalcellationTokenSource object.
To add this functionality in your application first of all, defina new private member variable in your form derived from class of time CancellationTokenSource named cancelToken:
- //Cancellation token for cancelling the invoke
- private CancellationTokenSource cancelToken = new CancellationTokenSource();
To cancel the task just add an cancel button and write single line in it:
- cancelToken.Cancel();
Add Parallel option instance to store the Cancellation Token
- ParallelOptions parOpts = new ParallelOptions();
- parOpts.CancellationToken = cancelToken.Token;
- parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
- try
- {
- Parallel.ForEach(dirs, parOpts, dir =>
- {
- parOpts.CancellationToken.ThrowIfCancellationRequested();
- try
- {
- lstFiles.AddRange(Directory.GetFiles(dir, "*.doc*", SearchOption.AllDirectories));
- }
- catch
- {
- // do nothing
- }
- });
- endTime = DateTime.Now;
- TimeSpan ts = endTime.Subtract(startTime);
- MessageBox.Show("Search Complete!! \nFiles Found:" + lstFiles.Count + "\n Time elapsed:" + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds);
- }
- catch (OperationCanceledException ex)
- {
- MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- }
OUTPUT:
I hope you enjoyed reading this. Please comment if you liked it and spread the words about it.
No comments:
Post a Comment