TAN WhoAMI

TAN WhoAMI

  • NA
  • 291
  • 0

How to use Background Worker in WPF?

Dec 26 2013 1:22 AM

I have tried this example of Background worker (http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx), and it works perfectly, showing the percentage of progress from 10% till 90%, and Done!

How do I implement it for my DoLongWork() below, which is taking some time in querying the database? I have tried the below code, and it does not work (that is it does not show the percentage, and the whole UI is not responsive till the results are out). Which portions did I do wrongly?

Below are my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Data;
using System.Globalization;
using System.IO;
using System.ComponentModel;

namespace TestSystemUtilisation
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string path1 = @"C:\DriveD\TESTS4WORK\TestSystemUtilisation\CostCenter\";
        string path = @"C:\DriveD\TESTS4WORK\TestSystemUtilisation\";
        string outputfilename = "Utilisation.txt";
        string[] CostCenterName = { "Analog", "Digital", "INT1", "INT2", "INT3", "Photo", "US-PF", "US-PXS"};
        string[] CostCenterNumber = { "130300", "130400", "130500", "130600", "130650", "120200", "120300", "120301"};

        private BackgroundWorker bw = new BackgroundWorker();

        public MainWindow()
        {
            InitializeComponent();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] formats = { "d/M/yyyy hh:mm tt" };
            var defaultDT_Start = DateTime.ParseExact("1/10/2013 07:30 AM", formats, new CultureInfo("en-US"), DateTimeStyles.None);
            DateTimePicker_Start.Value = defaultDT_Start;
            var defaultDT_End = DateTime.ParseExact("3/10/2013 05:00 PM", formats, new CultureInfo("en-US"), DateTimeStyles.None);
            DateTimePicker_End.Value = defaultDT_End;
            Update_ListBoxTestSystemsDefault();
            string[] hr = { "Whole Day", "Day Shift w/o OT", "Night Shift w/o OT", "Day Shift with OT", "Night Shift with OT",
                            "Day Shift w/o OT + Night Shift w/o OT", "Day Shift w/o OT + Night Shift with OT",
                            "Night Shift w/o OT + Day Shift with OT", "Day Shift with OT + Night Shift with OT"};
            comboBox_Base.ItemsSource = hr.ToList();
            comboBox_CostCenter.ItemsSource = CostCenterName.ToList();
        }
       
        private void Update_ListBoxTestSystemsDefault()
        {
            listBox_TestSystems.Items.Clear();
            string outputfilename = "Analog.txt";
            FileInfo file = new FileInfo(string.Concat(path1, outputfilename));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_TestSystems.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void comboBox_CostCenter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex = comboBox_CostCenter.SelectedIndex;
            listBox_TestSystems.Items.Clear();
            label_CostCenter.Content = CostCenterNumber[selectedIndex];
            FileInfo file = new FileInfo(string.Concat(path1, CostCenterName[selectedIndex],".txt"));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_TestSystems.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void comboBox_Base_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex = comboBox_Base.SelectedIndex;
            string[] hr = { "24", "8.8", "8.5", "11.55", "11.5", "17.3", "20.3", "20.05", "23.05" };
            string[] duration = { "00:00 AM - 11:59 PM", "07:30 AM - 05:00 PM", "11:00 PM - 07:45 AM", "07:30 AM - 08:00 PM", "08:00 PM - 07:45 AM",
                                  "07:30 AM - 05:00 PM + 11:00 PM - 07:45 AM", "07:30 AM - 05:00 PM + 08:00 PM - 07:45 AM", "11:00 PM - 07:45 AM + 07:30 AM - 08:00 PM",
                                  "07:30 AM - 08:00 PM + 08:00 PM - 07:45 AM" };

            if (comboBox_Base.SelectedIndex == selectedIndex)
                label_Base.Content = hr[selectedIndex];
                label_Duration.Content = duration[selectedIndex];
        }

        private void Update_ListBoxUtilisation()
        { 
            listBox_Utilisation.Items.Clear();
        
            FileInfo file = new FileInfo(string.Concat(path, outputfilename));
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                listBox_Utilisation.Items.Add(stRead.ReadLine());
            }
            stRead.Close();
        }

        private void Query2_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }

        private void DoLongWork()
        {
            TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter adapter = new TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter();
            TS_UtilisationDataSet.PPL_TESTSYSTEMS_UTILISATIONDataTable table = adapter.GetData();

            StreamWriter sw = new StreamWriter(string.Concat(path, outputfilename));

            Int32 Testtime_hr, Testtime_min;
           
            string[] formats = { "d/M/yyyy hh:mm:ss tt" };
            var Start = DateTime.ParseExact(DateTimePicker_Start.Text.ToString(), formats, new CultureInfo("en-US"), DateTimeStyles.None);
            var End = DateTime.ParseExact(DateTimePicker_End.Text.ToString(), formats, new CultureInfo("en-US"), DateTimeStyles.None);

            var SelectedTestSystems = new List<string>();
            var Testtime = new List<Int32>();
            var Utilisation1 = new List<double>();
            var Utilisation2 = new List<double>();
            var Utilisation3 = new List<double>();

            foreach (var arr in listBox_TestSystems.SelectedItems)
            {
                SelectedTestSystems.Add(arr.ToString());
            }

            string header1 = "SystemType Pure Testtime Utilisation1(%) Utilisation2(%)";
            string header2 = "========== ============= =============== ===============";

            sw.WriteLine(header1);
            sw.WriteLine(header2);

            TimeSpan ts = End - Start;
            int DifferenceInDays = ts.Days;
            double DifferenceInHours = ts.Hours + ts.Minutes / 60.0;

            for (int i = 0; i < SelectedTestSystems.Count(); i++)
            {
                for (int d = 0; d <= DifferenceInDays; d++)
                {
                    IEnumerable<DataRow> query =
                       from row in table.AsEnumerable()
                       where (row.Field<string>("SYSTEMTYPE") == SelectedTestSystems[i]) && (row.Field<DateTime?>("TS_START") > Start.AddDays(d)) && (row.Field<DateTime?>("TS_END") < Start.AddDays(d).AddHours(DifferenceInHours))
                       select row;                 

                    var TimeTest = query.Select(row => row.Field<Decimal?>("TIME_TEST")).Sum();
                    var TimeSystem = query.Select(row => row.Field<Decimal?>("TIME_SYSTEM")).Sum();
                    var TimeWait = query.Select(row => row.Field<Decimal?>("TIME_WAIT")).Sum();
                   
                    decimal? hr_per_day = Convert.ToDecimal(label_Base.Content.ToString());

                    decimal? Utilisation_1 = (TimeTest + TimeSystem) * 100 / (hr_per_day * 3600);
                    decimal? Utilisation_2 = (TimeTest + TimeSystem + TimeWait) * 100 / (hr_per_day * 3600);
                   
                    Testtime.Add(Convert.ToInt32(TimeTest));
                    Utilisation1.Add(Convert.ToDouble(string.Format("{0:N2}", Utilisation_1 / (DifferenceInDays + 1))));
                    Utilisation2.Add(Convert.ToDouble(string.Format("{0:N2}", Utilisation_2 / (DifferenceInDays + 1))));                   
                }

                Testtime_hr = Testtime.Sum() / 3600;
                Testtime_min = Testtime.Sum() / 60 - Testtime_hr * 60;
                sw.WriteLine("{0,8}{1,14}{2,17}{3,17}", SelectedTestSystems[i], string.Concat(Testtime_hr, "h ", Testtime_min, "min"), Utilisation1.Sum(), Utilisation2.Sum());
            }
            sw.Close();
            Update_ListBoxUtilisation();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    //System.Threading.Thread.Sleep(500);
                    Dispatcher.BeginInvoke(new Action(() => DoLongWork()));
                    worker.ReportProgress((i * 10));
                }
            }
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                textBox1.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                textBox1.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                textBox1.Text = "Done!";
            }
        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBox1.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}



Answers (1)