using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroundWorker
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
         backgroundWorker1.WorkerReportsProgress = true;
         backgroundWorker1.WorkerSupportsCancellation = true;
      }

      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
      {
         tsProgress.Value = 0;
         for (int i = 0; i < 100; i++)
         {
            if (backgroundWorker1.CancellationPending)
            {
               e.Cancel = true;
               return;
            }
            Thread.Sleep(100);
            backgroundWorker1.ReportProgress(i);
         }
      }

      private void backgroundWorker1_ProgressChanged(
         object sender, ProgressChangedEventArgs e)
      {
         tsProgress.Value = e.ProgressPercentage;
      }

      private void backgroundWorker1_RunWorkerCompleted(
         object sender, RunWorkerCompletedEventArgs e)
      {
         if (e.Cancelled)
         {
            tsProgress.Value = 0;
            MessageBox.Show("Długotrwałe zadanie zostało anulowane.");
         }
         else
            MessageBox.Show("Długotrwałe zadanie zostało ukończone.");
      }

      // rozpocznij zadanie drugoplanowe
      private void button1_Click(object sender, EventArgs e)
      {
         backgroundWorker1.RunWorkerAsync();
      }

      // anuluj zadanie drugoplanowe
      private void button2_Click(object sender, EventArgs e)
      {
         backgroundWorker1.CancelAsync();
      }
   }
}
