In this article I shall demonstrate how to do a file search using parallel programming in C#.
Before going through this article I strongly recommend you go through the basics of the Task Parallel Library and Parallel.Foreach mechanism in the .Net Framework 4.The demo application consists of a form with 2 button controls and 2 list box controls.Step 1: Design the form as shown.The purpose of this application:
Step 2: Create a class with the Search functionality code as shown.
CustomFileSearch class consists of the following 2 methods.
Let's discuss the FileSearch method. It consists of the following 4 parameters:
The button enable/disable and list box clearing functionality is done here. It is done in a separate task so that the main UI thread is independent of these functionalities. This is done by passing a Task Scheduler object to the Task.
First we get the information of all files ending with .cs extension as a FileInfo collection. Then the Parallel.ForEach is run on this collection. For each selected file the delegate is invoked with the current file name, listbox and button as parameters. This delegate invokes the method DisplaySearchedFile.DisplaySearchedFile
It consists of the following 3 parameters:
Each searched file is added to the list box as a separate task. This is to ensure that the processes that are running are not affected (synchronize the main thread and the current thread.). This is done by passing the Task Scheduler object to the Task.Step 3: Main Form:
In the form load event we have passed the Task Scheduler object to the constructor of the CustomFileSearch class.In the button click event I have hard-coded the drives as C drive and D drive. My machine consists of only C and D drives. You can change it to your own machine's drives.
Inside the button click we call the FileSearch method with the respective parameters as shown.
OutputBefore running the app, ensure that you have the privilege to read specific files in your computer via this application. Since I am having some privilege issues (company PC) I have used the same drive for the search functionality. For a better understanding I have shared the source code. Before running the application, ensure that you have the current drives hard-coded in the button clicks. If not please change it to your computer-specific drives.Just try to resize or move the application while running.
Diving Into OOP