How to print a document in background using C#
Many time-consuming tasks can be done asynchronously. This can be done using multithreaded applications. Fortunately visual studio .net has the background worker control does all the mundane multithreading efforts by itself
Let us go back to our good old select file application (as shown below). To the form add the background worker control, which will be placed on the tray.
Once the user clicks the OK button, the background worker is called using RunWorkerAsync method. This will execute the backgroundWorker1_DoWork event while the Windows form responds to the user actions.
private void buttonOK_Click(object sender, EventArgs e)
{
if (txtExcelFile.Text.Length == 0)
{
System.Console.Beep();
MessageBox.Show ("Select the file and continue...");
}
backgroundWorker1.RunWorkerAsync(txtExcelFile.Text);
}
Status of the process is updated to the Form
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Replace with the actual code of printing the document
String sFile = e.Argument.ToString();
for (int i1 = 1; i1 <>
{
for (int i2 = 1; i2 <>
{
toolStripStatusLabel1.Text = "Printing " + sFile + "...";
}
}
}
You can also use the backgroundWorker1.ReportProgress method to update the status through backgroundWorker1_ProgressChanged event
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripStatusLabel1.Text = e.ProgressPercentage.ToString() + " percent completed";
}
The completion of the background worker can be ascertained by the RunWorkerCompleted event
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
toolStripStatusLabel1.Text = "Printing completed";
}
How to run a process in background using .NET, How to handle background events in .NET