Introduction
The class explained here demonstrates a multi-threaded Linked Task Queue. This class allows you to add multiples tasks to multiple queues. Two queues may run simultaneously in different threads, but each queue will run one task at a time and one after the other.
Background
Once I came across a project where I had to do a lot of processor hungry tasks of copying files, compression and encryption etc. So, I created this easy to use framework to queue tasks and display their status. The demo project here was created in a hurry, and does not demonstrate all the features of the class.
Classes
Using the code
To use this code, first of all, add TaskQueue
member variables in your form or class, and then in the initialization code, create the queue using the TaskQueueTable class. Like shown below..
protected TaskQueue taskQueue;
public frmQueueDemo()
{
InitializeComponent();
taskQueue = TaskQueueTable.Instance.GetTaskQueue("Encryption");
taskQueue.TaskStarting +=
new TaskQueue.TaskStartingEeventHandler(taskQueue_TaskStarting);
}
Then, inherit the Task
class to create your classes and override the PerformTask
function. Like this..
public class EncriptFileTask : Task
{
public EncriptFileTask(string filePath) :
base("Encripting file " + filePath)
{
this.FilePath = filePath;
}
private string filePath;
public string FilePath {
get
{
return filePath;
}
set
{
filePath = value;
}
}
protected override void PerformTask(object param)
{
try
{
FileStream reader = File.OpenRead(FilePath);
RC4.rc4_key key = new RC4.rc4_key();
RC4.PrepareKey(System.Text.UTF8Encoding.ASCII.GetBytes(
"Task Queue Demo"), ref key);
RC4 rc4 = new RC4();
byte[] read = new byte[8];
long total = reader.Length;
long completed = 0;
while(reader.Position < total && !IsAborting)
{
int bRead = reader.Read(read, 0, 8);
completed += bRead;
RC4.rc4(ref read, bRead, ref key);
int percent = (int)((completed / (double)total) * 100);
OnProgress(percent);
}
reader.Close();
}
catch (Exception ex)
{
OnAddLog(ex.Message);
}
base.PerformTask(param);
}
}
Remember to call the base.PerformTask
function to be sure to call the proper events when the task finishes. Also remember to use the IsAborting
property to allow peaceful cancelation of a task.