运行效果:
前台代码:
- <Window x :Class="Waiting.Window1"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="后台忙" Height="94.635" Width="197.361">
- <Grid >
- <Button Content ="开始" HorizontalAlignment="Left" Margin="10,10,0,0" Name ="button1" VerticalAlignment="Top" Click="button1_Click" Width ="48" />
- <Label Name ="lab_pro" Content="" Height="25" VerticalAlignment ="Top" HorizontalAlignment="Left" Margin="80,20,0,0" />
- <!--动画代码,只要填写name属性即可-->
- <Grid Name ="loading" Visibility="Collapsed" Height="41" Grid.Row ="0" VerticalAlignment="Top" Margin="126,10,0,0" HorizontalAlignment="Left" Width ="42">
- <Grid.Resources>
- <DrawingBrush x :Key="brush" Stretch="None" AlignmentX ="Center" AlignmentY="Top">
- <DrawingBrush.Drawing>
- <GeometryDrawing Brush ="Black">
- <GeometryDrawing.Geometry>
- <EllipseGeometry RadiusX ="2" RadiusY="5"/>
- </GeometryDrawing.Geometry>
- </GeometryDrawing>
- </DrawingBrush.Drawing>
- </DrawingBrush>
- </Grid.Resources>
- <Rectangle x :Name="r01" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="0"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r02" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="30"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r03" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="60"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r04" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="90"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r05" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="120"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r06" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="150"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r07" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="180"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r08" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="210"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r09" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="240"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r10" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="270"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r11" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="300"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Rectangle x :Name="r12" Fill="{StaticResource brush}" Opacity ="0.5" RenderTransformOrigin="0.5,0.5">
- <Rectangle.RenderTransform>
- <RotateTransform Angle ="330"/>
- </Rectangle.RenderTransform>
- </Rectangle>
- <Grid.Triggers>
- <EventTrigger RoutedEvent ="Grid.Loaded">
- <BeginStoryboard>
- <Storyboard RepeatBehavior ="Forever">
- <DoubleAnimation Storyboard.TargetName ="r01" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.00000" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r02" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.08333" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r03" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.16666" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r04" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.24999" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r05" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.33332" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r06" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.41665" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r07" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.49998" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r08" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.58331" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r09" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.66664" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r10" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.74997" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r11" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.83330" To="0"/>
- <DoubleAnimation Storyboard.TargetName ="r12" Storyboard.TargetProperty="Opacity" AutoReverse="True" Duration="0:0:0.08333" BeginTime ="0:0:0.91663" To="0"/>
- </Storyboard>
- </BeginStoryboard>
- </EventTrigger>
- </Grid.Triggers>
- </Grid>
- </Grid >
- </Window>
后台代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- 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.Shapes;
- namespace Waiting
- {
- /// <summary>
- /// Window1.xaml 的交互逻辑
- /// </summary>
- public partial class Window1 : Window
- {
- public Window1()
- {
- InitializeComponent();
- }
- BackgroundWorker bgMeet;
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- bgMeet = new BackgroundWorker ();
- //能否报告进度更新
- bgMeet.WorkerReportsProgress = true;
- //要执行的后台任务
- bgMeet.DoWork += new DoWorkEventHandler (bgMeet_DoWork);
- //进度报告方法
- bgMeet.ProgressChanged += new ProgressChangedEventHandler (bgMeet_ProgressChanged);
- //后台任务执行完成时调用的方法
- bgMeet.RunWorkerCompleted += new RunWorkerCompletedEventHandler (bgMeet_RunWorkerCompleted);
- bgMeet.RunWorkerAsync(); //任务启动
- }
- //执行任务
- void bgMeet_DoWork(object sender, DoWorkEventArgs e)
- {
- //开始播放等待动画
- this.Dispatcher.Invoke(new Action(() =>
- {
- loading.Visibility = System.Windows. Visibility.Visible;
- }));
- //开始后台任务
- GetData();
- }
- //报告任务进度
- void bgMeet_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- this.Dispatcher.Invoke(new Action(() =>
- {
- this.lab_pro.Content = e.ProgressPercentage + "%";
- }));
- }
- //任务执行完成后更新状态
- void bgMeet_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- loading.Visibility = System.Windows. Visibility.Collapsed;
- this.Dispatcher.Invoke(new Action(() =>
- {
- this.lab_pro.Content = "完成" ;
- }));
- }
- //模拟耗时任务
- public void GetData()
- {
- for (int i = 0; i < 6; i++)
- {
- bgMeet.ReportProgress(20*i);
- System.Threading. Thread.Sleep(400);
- }
- }
- }
- }
C# BackgroundWorker 详解
在C#程序中,经常会有一些耗时较长的CPU密集型运算,如果直接在 UI 线程执行这样的运算就会出现UI不响应的问题。解决这类问题的主要途径是使用多线程,启动一个后台线程,把运算操作放在这个后台线程中完成。但是原生接口的线程操作有一些难度,如果要更进一步的去完成线程间的通信就会难上加难。
还好 .NET 类库中提供了一个叫做 BackgroundWorker 的类可以比较优雅的解决这类问题。虽然BackgroundWorker 类使用起来比较简单,但其中还是有一些需要注意的细节,下面我们就通过 demo 程序介绍它的主要用法。我们在 demo中计算1到100的累加和,为了演示,每次计算都 sleep 600毫秒,demo 的UI为:
用法概述
在窗体上构建一个BackgroundWorker 实例,在它的 DoWork事件处理函数中添加耗时的运算,然后调用它的RunWorkerAsync方法就可以了。
private BackgroundWorker _demoBGWorker = new BackgroundWorker(); _demoBGWorker.DoWork += BGWorker_DoWork; _demoBGWorker.RunWorkerAsync(); private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { //在这里执行耗时的运算。 int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } }
是不是有点太简单了?那么让我们考虑下面的问题:
如果我们想要把参数传递给运算过程该怎么做?
在运算过程中我们希望把实时的信息显示在UI上该怎么办?
如果我们想要取消正在进行的运算该怎么办?
如果运算过程出现异常我们又该如何处理?
接下来我们就一个一个的处理这些问题。
把参数传递给运算过程
直接把100写死到运算过程中可不好,我们还打算允许用户指定求和的范围呢!所以需要把100作为参数传递给计算过程。在概述中我们通过调用RunWorkerAsync方法启动计算过程,其实这个方法可以接受一个 object 类型的参数。通过它我们就可以把任何数据传递给计算过程:
//别忘了设置滚动条。 this.progressBarSum.Maximum = 100; _demoBGWorker.RunWorkerAsync(100); //下面是更新后的 BGWorker_DoWork 方法: private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { //在这里执行耗时的运算。 int endNumber = 0; if(e.Argument != null) { endNumber = (int)e.Argument; } int sum = 0; for (int i = 0; i <= endNumber; i++) { sum += i; } }
BGWorker_DoWork事件处理函数通过参数 e 的Argument属性传来了我们期望的运算信息。
把消息传递给UI
由于计算过程比较长,我们在通过进度条来显示当前进度的同时,还希望能实时的把计算的中间结果显示在UI上。当然,BackgroundWorker对这个用例也提供了很好的支持。它允许我们在执行计算的过程中给UI线程发送消息,下面看看具体的做法:
_demoBGWorker.WorkerReportsProgress = true; _demoBGWorker.ProgressChanged += BGWorker_ProgressChanged;
首先要把WorkerReportsProgress 属性设置为 true,然后为ProgressChanged 事件添加处理方法:
private void BGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //修改进度条的显示。 this.progressBarSum.Value = e.ProgressPercentage; //如果有更多的信息需要传递,可以使用 e.UserState 传递一个自定义的类型。 //这是一个 object 类型的对象,您可以通过它传递任何类型。 //我们仅把当前 sum 的值通过 e.UserState 传回,并通过显示在窗口上。 string message = e.UserState.ToString(); this.labelSum.Text = message; }
继续更新 BGWorker_DoWork方法:
private void BGWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgWorker = sender as BackgroundWorker; int endNumber = 0; if(e.Argument != null) { endNumber = (int)e.Argument; } int sum = 0; for (int i = 0; i <= endNumber; i++) { sum += i; string message = "Current sum is: " + sum.ToString(); //ReportProgress 方法把信息传递给 ProcessChanged 事件处理函数。 //第一个参数类型为 int,表示执行进度。 //如果有更多的信息需要传递,可以使用 ReportProgress 的第二个参数。 //这里我们给第二个参数传进去一条消息。 bgWorker.ReportProgress(i, message); Thread.Sleep(600); } }
OK,现在已经可以看到进度条和执行信息的更新了。
取消操作
在执行过程中允许用户取消当前的操作是一个基本的设计,BackgroundWorker自然有很好的支持:
_demoBGWorker.WorkerSupportsCancellation = true;
和WorkerReportsProgress属性一样,如果要支持取消操作我们需要设置 WorkerSupportsCancellation属性为 true。并且还要在BGWorker_DoWork方法中进行支持,在 for 循环中 Thread.Sleep(600)后面添加代码:
bgWorker.ReportProgress(i, message); Thread.Sleep(600); //在操作的过程中需要检查用户是否取消了当前的操作。 if (bgWorker.CancellationPending == true) { e.Cancel = true; break; }
如果检测到用户点击的取消按钮,就退出当前的计算过程。下面是点击取消按钮时要调用的代码:
_demoBGWorker.CancelAsync();
现在已经可以支持取消操作了,赶快试试吧!
异常处理
如果在计算过程中发生了异常该怎么处理?有没有办法知道计算过程已经结束?当然要有,即便是正常的结束也需要拿到计算的结果。
_demoBGWorker.RunWorkerCompleted += BGWorker_RunWorkerCompleted; private void BGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //如果用户取消了当前操作就关闭窗口。 if (e.Cancelled) { this.Close(); } //计算已经结束,需要禁用取消按钮。 this.btnCancel.Enabled = false; //计算过程中的异常会被抓住,在这里可以进行处理。 if (e.Error != null) { Type errorType = e.Error.GetType(); switch (errorType.Name) { case "ArgumentNullException": case "MyException": //do something. break; default: //do something. break; } } //计算结果信息:e.Result //use it do something. }
RunWorkerCompleted 事件处理函数会在DoWork 事件处理函数返回后被调用。通过它我们可以进行一些运算结束后的操作,比如禁用取消按钮,异常处理,结果显示等。
注意,如果想要拿到 e.Result,您需要在BGWorker_DoWork方法中设置 e.Result属性,如:
e.Result = sum;
总结,BackgroundWorker 类功能完善且使用简便,实在是处理异步耗时操作的利器!