如何在WPF中使用Background Worker? [英] How to use Background Worker in WPF?

查看:66
本文介绍了如何在WPF中使用Background Worker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了这个背景工作者的示例( http ://msdn.microsoft.com/zh-CN/library/cc221403(v = vs.95).aspx ),并且效果很好,显示了进度百分比 从10%到90%,然后完成!

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!

如何为下面的DoLongWork()实现它,这需要花费一些时间来查询数据库?我已经尝试了下面的代码,但是它不起作用(也就是说,它没有显示百分比,并且整个UI在结果显示出来之前都没有响应). 我做错了哪些部分?

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?

下面是我的代码:

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.Data;
使用System.Globalization;
使用System.IO;
使用System.ComponentModel;

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;

命名空间TestSystemUtilisation
{
    ///< summary>
    ///MainWindow.xaml的交互逻辑
    ///</summary>
   公共局部类MainWindow:Window
    {
      字符串路径1 = @"C:\ DriveD \ TESTS4WORK \ TestSystemUtilisation \ CostCenter \";
      字符串路径= @"C:\ DriveD \ TESTS4WORK \ TestSystemUtilisation \";
      字符串outputfilename ="Utilisation.txt";
       string [] CostCenterName = {模拟",数字","INT1","INT2","INT3",照片","US-PF","US-PXS"} ;
       string [] CostCenterNumber = {"130300","130400","130500","130600","130650","120200","120300","120301"}}

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"};

      私人BackgroundWorker bw = new BackgroundWorker();

        private BackgroundWorker bw = new BackgroundWorker();

      公共MainWindow()
       {
           InitializeComponent();
           bw.WorkerReportsProgress = true;
           bw.WorkerSupportsCancellation = true;
           bw.DoWork + =新的DoWorkEventHandler(bw_DoWork);
           bw.ProgressChanged + =新的ProgressChangedEventHandler(bw_ProgressChanged);
           bw.RunWorkerCompleted + =新的RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
       }

        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);
        }

      私有void Window_Loaded(对象发送者,RoutedEventArgs e)
       {
           string []格式= {"d/M/yyyy hh:mm tt" };
           var defaultDT_Start = DateTime.ParseExact("2013年1月10日07:30",格式,新的CultureInfo("en-US"),DateTimeStyles.None);
           DateTimePicker_Start.Value = defaultDT_Start;
           var defaultDT_End = DateTime.ParseExact("2013年3月10日05:00 PM",格式,新的CultureInfo("en-US"),DateTimeStyles.None);
           DateTimePicker_End.Value = defaultDT_End;
           Update_ListBoxTestSystemsDefault();
           string [] hr = {"Whole Day",不带OT的日班",不带OT的夜班",带OT的日班",带OT的夜班",
              nbsp; bsp    不带OT的白班+不带OT的白班",不带OT的白班+夜班" OT",
              nbsp; bsp    不带OT的夜班+带OT的日班",带OT的日班+夜班" 与OT"};
           comboBox_Base.ItemsSource = hr.ToList();
           comboBox_CostCenter.ItemsSource = CostCenterName.ToList();
       }
      
      私有无效Update_ListBoxTestSystemsDefault()
       {
           listBox_TestSystems.Items.Clear();
          字符串outputfilename ="analog.txt";
           FileInfo文件=新的FileInfo(string.Concat(path1,outputfilename));
           StreamReader stRead = file.OpenText();
           while(!stRead.EndOfStream)
           {
                             listBox_TestSystems.Items.Add(stRead.ReadLine());
           }
           stRead.Close();
       }

        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();
        }

      私有void comboBox_CostCenter_SelectionChanged(对象发送者,SelectionChangedEventArgs e)
       {
           int selectedIndex = comboBox_CostCenter.SelectedIndex;
           listBox_TestSystems.Items.Clear();
           label_CostCenter.Content = CostCenterNumber [selectedIndex];
           FileInfo文件=新的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_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();
        }

      私有void comboBox_Base_SelectionChanged(对象发送方,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",
              nbsp; bsp         " 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",
              nbsp; bsp         " 07:30 AM-08:00 PM + 08:00 PM-07:45 AM" };

        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" };

          如果(comboBox_Base.SelectedIndex == selectedIndex)
                             label_Base.Content = hr [selectedIndex];
                             label_Duration.Content =持续时间[selectedIndex];
       }

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

      私有void Update_ListBoxUtilisation()
       { 
           listBox_Utilisation.Items.Clear();
       
           FileInfo文件=新FileInfo(string.Concat(路径,outputfilename));
           StreamReader stRead = file.OpenText();
           while(!stRead.EndOfStream)
           {
                             listBox_Utilisation.Items.Add(stRead.ReadLine());
           }
           stRead.Close();
       }

        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();
        }

      私有void Query2_Click(对象发送者,RoutedEventArgs e)
       {
          如果(bw.IsBusy!= true)
           {
                             bw.RunWorkerAsync();
           }
       }

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

      私人void DoLongWork()
       {
           TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter适配器=新的TS_UtilisationDataSetTableAdapters.PPL_TESTSYSTEMS_UTILISATIONTableAdapter();
           TS_UtilisationDataSet.PPL_TESTSYSTEMS_UTILISATIONDataTable table = adapter.GetData();

        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 =新的StreamWriter(string.Concat(path,outputfilename));

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

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

            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>();

            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(listBox_TestSystems.SelectedItems中的var arr)
           {
                             SelectedTestSystems.Add(arr.ToString());
           }

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

          字符串标头1 ="SystemType纯测试时间利用率1(%)利用率2(%)";
          字符串标题2 ="============================================ ========;

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

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

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

           TimeSpan ts =结束-开始;
           int DifferenceInDays = ts.Days;
           double DifferenceInHours = ts.Hours + ts.Minutes/60.0;

            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>查询=
             从table.AsEnumerable()中的行开始
             其中(row.Field< string>("SYSTEMTYPE")== SelectedTestSystems [i])&& (row.Field< DateTime?>(``TS_START'')) > Start.AddDays(d))&& (row.Field< DateTime?>(" TS_END"))< Start.AddDays(d).AddHours(DifferenceInHours))
             选择行            

            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();
                   
                   小数点? hr_per_day = Convert.ToDecimal(label_Base.Content.ToString());

                    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());

             小数点? Utilisation_1 =(TimeTest + TimeSystem)* 100/(hr_per_day * 3600);
                   小数点? 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)))));; ;        
                             }

                    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],字符串.Concat(Testtime_hr,"h",Testtime_min,"min"),Utilisation1.Sum(), Utilisation2.Sum());
           }
           sw.Close();
           Update_ListBoxUtilisation();
       }

                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();
        }

      私人void bw_DoWork(对象发送者,DoWorkEventArgs e)
       {
           BackgroundWorker worker =发送者为BackgroundWorker;

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

           for(int i = 1;(i&=; 10); i ++)
           {
                            如果((worker.CancellationPending == true))
                             {
                    e.Cancel = true;
                   休息;
                             }
                            其他
                             {
                    //执行耗时的操作并报告进度.
                    //System.Threading.Thread.Sleep(500);
                    Dispatcher.BeginInvoke(new Action(()=> DoLongWork()));
                    worker.ReportProgress((i * 10));
                             }
           }
       }

            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));
                }
            }
        }

      私有void bw_RunWorkerCompleted(对象发送者,RunWorkerCompletedEventArgs e)
       {
          如果((e.Cancelled == true))
           {
                             textBox1.Text =已取消!";
           }

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

          否则if(!(e.Error == null))
           {
                             textBox1.Text =("错误:" + e.Error.Message);
           }

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

          其他
           {
                             textBox1.Text ="Done!";
           }
       }

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

      私人空白bw_ProgressChanged(对象发送者,ProgressChangedEventArgs e)
       {
           textBox1.Text =(e.ProgressPercentage.ToString()+%");
       }
    }
}

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

推荐答案

只需将DoLongWork函数代码复制到BackgroundWorker_DoWork事件中,然后在您要在UI中更新进度的适当位置调用ReportProgress. 

Just copy your DoLongWork function code into BackgroundWorker_DoWork event and call ReportProgress at the appropriate places where you want to update the progress in the UI. 


这篇关于如何在WPF中使用Background Worker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆