namespace BackWorker
{
///
/// Created by Mss 31/8/09
/// Multi threading implementation
///
public partial class FileCopyWorker : Form
{
string SourcePath, DestPath;
private void btnStartCopy_Click(object sender, EventArgs e)
{
bgwWorker = new BackgroundWorker();
bgwWorker.WorkerReportsProgress = true;
bgwWorker.DoWork += new DoWorkEventHandler(bgwWorker_DoWork);
bgwWorker.ProgressChanged+=new ProgressChangedEventHandler(bgwWorker_ProgressChanged);
SourcePath = DestPath = string.Empty;
SourcePath = @"D:\ImportOCR Test files\Child\Child\001\CDS001.txt";
DestPath = @"C:\CopyoFQuarantine";
//Aynchronous call to the Complex large execution time method
//This will raise DoWork event
bgwWorker.RunWorkerAsync(this);
//
// Send argument to our worker thread
//
//backgroundWorker1.RunWorkerAsync(test);
}
void bgwWorker_DoWork(object sender, DoWorkEventArgs e)
{
//
// e.Argument always contains whatever was sent to the background worker
// in RunWorkerAsync. We can simply cast it to its original type.
//
//TestObject argumentTest = e.Argument as TestObject;
CopyFiles(SourcePath, DestPath);
}
private void CopyFiles(string SourcePath, string DestPath)
{
try
{
int i = 0;
do
{
//Thread.Sleep(200);
File.Copy(SourcePath, DestPath, true);
i++;
//Updating the progress value to control on Main Thread
lblStatus.Invoke(new MethodInvoker(delegate { lblStatus.Text = String.Format("{0} in progress",Convert.ToString(i * 2)); }));
//Background worker progress event, we can pass progress value to this event.
// If we pass like this, we can access main thread controls without use of Method Invoker
bgwWorker.ReportProgress(i*2, "In Progress");
} while (i < 50);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
///
/// This is on the main thread, so we can update a TextBox or anything.
///
private void bgwWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStatus.Text = e.ProgressPercentage.ToString()+" in progress";
}
///
/// This is on the main thread, so we can update a TextBox or anything.
///
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblStatus.Text = "Copy completed successsfully";
}
}
}