using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;



using System.ComponentModel;
namespace WpfBackgroundWorker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker worker;
        public MainWindow()
        {
            InitializeComponent();

        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            btnStart.IsEnabled = false;
            btnCancel.IsEnabled = true;

            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWrk;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += RunWorkerCompleted;
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            ProgressBar1.Maximum = 50;
            worker.RunWorkerAsync();
        }

        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                MessageBox.Show("متوقف شد");
            else
                MessageBox.Show("تمام شد");

            btnStart.IsEnabled = true;
            btnCancel.IsEnabled = false;
        }

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

        private void worker_DoWrk(object sender, DoWorkEventArgs e)
        {
           for(int i=1;i<=50;i++)
            {
                if(worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                this.Dispatcher.Invoke(() =>
                {
                    txtTime.Text = DateTime.Now.ToLongTimeString();
                });

                System.Threading.Thread.Sleep(200);

                worker.ReportProgress(i);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
         
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            worker.CancelAsync();
        }
    }
}
