Hi friends,
For testing and learning purposes, I tried to write a code which simulates some calculations. I used BackGroundWorker to avoid GUI freeze during calculation. My problem is that I want to make change in UI, for example, changing a button's text. I added it to DoWork section of my code. Consider that my operations order needs to be kept. There is runtime error says cross-thread exception. I think I have to use Invoke and Delegate for solving my problem. Please write me a code for solving this problem. I would learn from your code.
Thanks.
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- button1.Text = "processing";
- int sum = 0;
- for (int i = 0; i <= 100; i++)
- {
- Thread.Sleep(100);
- sum = sum + i;
- backgroundWorker1.ReportProgress(i);
- if (backgroundWorker1.CancellationPending)
- {
- e.Cancel = true;
- backgroundWorker1.ReportProgress(0);
- return;
- }
- }
- e.Result = sum;
- }
-
-
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- progressBar1.Value = e.ProgressPercentage;
- label1.Text = e.ProgressPercentage + "%";
-
- }
-
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- if (e.Cancelled)
- {
- label1.Text = "Process canceled";
- }
- else if (e.Error != null)
- {
- label1.Text = e.Error.Message;
- }
- else
- {
- label1.Text = "Result: " + e.Result.ToString();
- }
-
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- if (!backgroundWorker1.IsBusy)
- {
- backgroundWorker1.RunWorkerAsync();
- }
- else
- {
- MessageBox.Show("Busy processing!. Please wait...");
- }
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- if (backgroundWorker1.IsBusy)
- {
- backgroundWorker1.CancelAsync();
- }
- else
- {
- label1.Text = "No operation is running to cancel.";
- }
- }
- }