private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Long-running operation // Ex: Calculate the factorial of a number int num = (int) e.Argument; int result = 1; for (int i = 1; i <= num; i++) result *= i; // Return the result as the result of the background operation e.Result = result; } private void button1_Click(object sender, EventArgs e) { // Start the background worker backgroundWorker1.RunWorkerAsync(5); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Update the UI with the result of the background operation // Ex: Display the factorial of the number int result = (int) e.Result; MessageBox.Show("Factorial is " + result); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Long-running operation // Ex: Copy a large file string sourceFile = (string) e.Argument; string destinationFile = @"C:\Destination\LargeFile.txt"; using (FileStream sourceStream = File.Open(sourceFile, FileMode.Open)) using (FileStream destinationStream = File.Create(destinationFile)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { destinationStream.Write(buffer, 0, bytesRead); // Check for cancellation and set the Cancel flag if necessary if (backgroundWorker1.CancellationPending) { e.Cancel = true; break; } } } } private void button1_Click(object sender, EventArgs e) { // Start the background worker backgroundWorker1.RunWorkerAsync(@"C:\Source\LargeFile.txt"); } private void button2_Click(object sender, EventArgs e) { // Cancel the background operation if it is running if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Handle the completion or cancellation of the background operation if (e.Cancelled) MessageBox.Show("Operation cancelled."); else if (e.Error != null) MessageBox.Show("An error occurred: " + e.Error.Message); else MessageBox.Show("Operation completed successfully."); }Package/Library: The System.ComponentModel.DoWorkEventArgs class is part of the .NET Framework Class Library, which is a core part of the Microsoft .NET Framework. It can be accessed by adding the System.ComponentModel namespace to the project and referencing the appropriate assembly (such as System.dll).