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:
- Load the files into list boxes.
- The user is able to perform the button clicks simultaneously.
- The user is able to close the application before the file search.
- Responsive UI: the user can move or resize the application during runtime.
Step 2: Create a class with the Search functionality code as shown.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading.Tasks;
- using System.Threading;
- using System.IO;
-
- namespace ParallelFileSearch
- {
- public class CustomFileSearch
- {
- public static TaskScheduler uiScheduler;
- public CustomFileSearch(TaskScheduler taskScheduler)
- {
- uiScheduler = taskScheduler;
- }
- static void DisplaySearchedFile(string file, ListBox listBox, Button button)
- {
-
- Task.Factory.StartNew(() =>
- {
- if (file != string.Empty)
- {
- listBox.Items.Add(file);
- }
- else
- {
- button.Enabled = true;
- }
- }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
- }
- public void FileSearch(DirectoryInfo info, ListBox listBox, Button button, Action<string, ListBox, Button> currentFile)
- {
- Task.Factory.StartNew(() =>
- {
-
- listBox.Items.Clear();
- button.Enabled = false;
- }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
-
- IEnumerable<FileInfo> fileInfo = info.EnumerateFiles("*.cs", SearchOption.AllDirectories);
- Parallel.ForEach(fileInfo, s =>
- {
- Thread.Sleep(300);
- currentFile(s.FullName, listBox, button);
- });
-
-
- currentFile(string.Empty, listBox, button);
- }
- }
- }
CustomFileSearch class consists of the following 2 methods.
- FileSearch
- DisplaySearchedFile
Let's discuss the FileSearch method. It consists of the following 4 parameters:
- DirectoryInfo info: This accepts the directory for file search. It is supplied from the client side.
- ListBox listBox: This accepts the listbox from the client side. This is used in the method DisplaySearchedFile.
- Button button: This accepts the button from the client side. This is used in the method DisplaySearchedFile.
- Action<string, ListBox, Button> currentFile: This is an action delegate that accepts parameters of string type, Listbox type and Button type.
- Task.Factory.StartNew(() =>
- {
-
- listBox.Items.Clear();
- button.Enabled = false;
- }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
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.
- IEnumerable<FileInfo> fileInfo = info.EnumerateFiles("*.cs", SearchOption.AllDirectories);
- Parallel.ForEach(fileInfo, s =>
- {
- Thread.Sleep(300);
- currentFile(s.FullName, listBox, button);
- });
-
-
-
- currentFile(string.Empty, listBox, button);
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
- static void DisplaySearchedFile(string file, ListBox listBox, Button button)
- {
-
- Task.Factory.StartNew(() =>
- {
- if (file != string.Empty)
- {
- listBox.Items.Add(file);
- }
- else
- {
- button.Enabled = true;
- }
- }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
- }
It consists of the following 3 parameters:
- string file: Searched file
- ListBox listBox
- Button button
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:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Threading.Tasks;
- using System.Threading;
- using System.Diagnostics;
- using System.Collections;
-
- namespace ParallelFileSearch
- {
- public partial class ParallelSearch : Form
- {
- TaskScheduler uiScheduler;
- CustomFileSearch customFileSearch;
- public ParallelSearch()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
- customFileSearch = new CustomFileSearch(uiScheduler);
- }
- private void btnDrive1_Click(object sender, EventArgs e)
- {
- DirectoryInfo dirInfo = new DirectoryInfo(@"C:\ ");
- Task.Factory.StartNew(() => customFileSearch.FileSearch(dirInfo, lstFile1, btnDrive1, CustomFileSearch.DisplaySearchedFile));
- }
- private void btnDrive2_click(object sender, EventArgs e)
- {
- DirectoryInfo dirInfo = new DirectoryInfo(@"D:\ ");
- Task.Factory.StartNew(() => customFileSearch.FileSearch(dirInfo, lstFile2, btnDrive2, CustomFileSearch.DisplaySearchedFile));
- }
- }
- }
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.
- DirectoryInfo dirInfo = new DirectoryInfo(@"C:\ ");
- DirectoryInfo dirInfo = new DirectoryInfo(@"D:\ ");
Inside the button click we call the FileSearch method with the respective parameters as shown.
- Task.Factory.StartNew(() => customFileSearch.FileSearch(dirInfo, lstFile1, btnDrive1, CustomFileSearch.DisplaySearchedFile));
- Task.Factory.StartNew(() => customFileSearch.FileSearch(dirInfo, lstFile2, btnDrive2, CustomFileSearch.DisplaySearchedFile));
Output
Before 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.