WPF BackGroundWord 异步加载更新进度条示例

 1 <Window x:Class="AsynchronousLoading.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:AsynchronousLoading"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="700" Width="1000" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen">
 9     <Grid>
10         <ListView HorizontalAlignment="Left" x:Name="ItemListView" FontSize="30" Width="389" ></ListView>
11
12     </Grid>
13 </Window>
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;

namespace AsynchronousLoading
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public  List<string> list = new List<string>();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GetDataWin getDataWin = new GetDataWin();
            getDataWin.list = list;
            getDataWin.count = 100;

            if (getDataWin.ShowDialog()==true) //数据全部获取完成之后再执行下一步操作 反正不执行
            {
                LoadData loadData = new LoadData(this.list,this.ItemListView);
                if (loadData.ShowDialog() == true)
                {
                    MessageBox.Show("操作完成!");
                }

            }

        }
    }
}
namespace AsynchronousLoading
{
    /// <summary>
    /// 自定义传参类
    /// </summary>
    public  class CommentModel
    {
        /// <summary>
        /// 第几个
        /// </summary>
        public int num { get; set; }
        /// <summary>
        /// 当前添加的字符串项
        /// </summary>
        public string itemStr { get; set; }
    }
}
 1 <Window x:Class="AsynchronousLoading.GetDataWin"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:AsynchronousLoading"
 7         mc:Ignorable="d"
 8         Title="正在获取数据..." Height="170" Width="800"  x:Name="GetDataWindow" Loaded="GetDataWindow_Loaded" WindowStartupLocation="CenterScreen">
 9     <Grid>
10         <ProgressBar x:Name="GetDataPro" Height="20"    Minimum="0" />
11         <Label x:Name="arealyNum" Content="已获得:   0" Height="30" FontSize="15" Foreground="Green" Margin="90,20,551,90"/>
12         <Label x:Name="noNum" Content="未获得:  0" Height="30"  FontSize="15" Foreground="Red" Margin="291,10,345,79"/>
13         <Label x:Name="totalCount" Content="共计数据: 0 条" FontSize="15" Height="30" Margin="524,10,107,79"/>
14         <Button x:Name="btnCancel" Content="取消" FontSize="15" Height="20" Margin="347,81,297,18" Click="BtnCancel_Click" />
15     </Grid>
16 </Window>
using System;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System.Threading;
namespace AsynchronousLoading
{
    /// <summary>
    /// GetDataWin.xaml 的交互逻辑
    /// </summary>
    public partial class GetDataWin : Window
    {
        public List<string> list { get; set; } //添加的数据集合
        public int count { get; set; } //要添加的集合的元素个数
        BackgroundWorker bgWork = new BackgroundWorker();
        public GetDataWin()
        {

            InitializeComponent();

            bgWork.WorkerReportsProgress = true; //支持报告进度
            bgWork.WorkerSupportsCancellation = true; //支持取消
        }

        private void GetDataWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.GetDataPro.Maximum = this.count;
            this.totalCount.Content = "共计数据:  " + this.count + "条!";
            bgWork.DoWork += BgWork_DoWork; //异步操作
            bgWork.RunWorkerAsync(count); //开始异步操作
            bgWork.ProgressChanged += BgWork_ProgressChanged; //更新进度条
            bgWork.RunWorkerCompleted += BgWork_RunWorkerCompleted; //任务执行完成之后引发的事件
        }
        //后台异步执行
        private void BgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;
            int count =(int)e.Argument;
            for (int i = 0; i < count; i++)
            {
                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                this.list.Add((i+1).ToString());
                backgroundWorker.ReportProgress(i,i.ToString());
                Thread.Sleep(1000);
            }
            e.Result = this.list; //事件处理完成之后的结果
        }
        //取消后台执行
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            bgWork.CancelAsync();
        }
        //更新进度条UI 显示进度
        private void BgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int num = int.Parse(e.UserState.ToString());
            this.arealyNum.Content = "已获得:  " + num;
            this.noNum.Content = "未获得:  " + (this.count - num);
            this.GetDataPro.Value = e.ProgressPercentage;
        }
        //处理完成
        private void BgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) //任务取消
            {
                MessageBox.Show("任务取消执行!");
                this.Close();
            }
            else if (e.Error!=null) //出现异常
            {
                MessageBox.Show("出现异常啦!" + e.Error.Message + e.Error.Source + e.Error.StackTrace);
            }
            else
            {
                this.DialogResult = true; //设置窗体的返回值为true 表示已经获取全部的数据
                this.Close(); //操作完成之后关闭窗口
            }

        }

    }
}
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Windows;
 4 using System.ComponentModel;
 5 using System.Threading;
 6 namespace AsynchronousLoading
 7 {
 8     /// <summary>
 9     /// GetDataWin.xaml 的交互逻辑
10     /// </summary>
11     public partial class GetDataWin : Window
12     {
13         public List<string> list { get; set; } //添加的数据集合
14         public int count { get; set; } //要添加的集合的元素个数
15         BackgroundWorker bgWork = new BackgroundWorker();
16         public GetDataWin()
17         {
18
19             InitializeComponent();
20
21             bgWork.WorkerReportsProgress = true; //支持报告进度
22             bgWork.WorkerSupportsCancellation = true; //支持取消
23         }
24
25         private void GetDataWindow_Loaded(object sender, RoutedEventArgs e)
26         {
27             this.GetDataPro.Maximum = this.count;
28             this.totalCount.Content = "共计数据:  " + this.count + "条!";
29             bgWork.DoWork += BgWork_DoWork; //异步操作
30             bgWork.RunWorkerAsync(count); //开始异步操作
31             bgWork.ProgressChanged += BgWork_ProgressChanged; //更新进度条
32             bgWork.RunWorkerCompleted += BgWork_RunWorkerCompleted; //任务执行完成之后引发的事件
33         }
34         //后台异步执行
35         private void BgWork_DoWork(object sender, DoWorkEventArgs e)
36         {
37             BackgroundWorker backgroundWorker = sender as BackgroundWorker;
38             int count =(int)e.Argument;
39             for (int i = 0; i < count; i++)
40             {
41                 if (backgroundWorker.CancellationPending)
42                 {
43                     e.Cancel = true;
44                     return;
45                 }
46                 this.list.Add((i+1).ToString());
47                 backgroundWorker.ReportProgress(i,i.ToString());
48                 Thread.Sleep(1000);
49             }
50             e.Result = this.list; //事件处理完成之后的结果
51         }
52         //取消后台执行
53         private void BtnCancel_Click(object sender, RoutedEventArgs e)
54         {
55             bgWork.CancelAsync();
56         }
57         //更新进度条UI 显示进度
58         private void BgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
59         {
60             int num = int.Parse(e.UserState.ToString());
61             this.arealyNum.Content = "已获得:  " + num;
62             this.noNum.Content = "未获得:  " + (this.count - num);
63             this.GetDataPro.Value = e.ProgressPercentage;
64         }
65         //处理完成
66         private void BgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
67         {
68             if (e.Cancelled) //任务取消
69             {
70                 MessageBox.Show("任务取消执行!");
71                 this.Close();
72             }
73             else if (e.Error!=null) //出现异常
74             {
75                 MessageBox.Show("出现异常啦!" + e.Error.Message + e.Error.Source + e.Error.StackTrace);
76             }
77             else
78             {
79                 this.DialogResult = true; //设置窗体的返回值为true 表示已经获取全部的数据
80                 this.Close(); //操作完成之后关闭窗口
81             }
82
83         }
84
85
86     }
87 }
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Threading;
namespace AsynchronousLoading
{
    /// <summary>
    /// LoadData.xaml 的交互逻辑
    /// </summary>
    public partial class LoadData : Window
    {

        private ListView listView { get; set; } //向列表中添加
        private List<string> list {get;set;} //源数据集合
        BackgroundWorker bgWork = new BackgroundWorker();
        public LoadData(List<string> list, ListView listViews)
        {
            InitializeComponent();
            if (list!=null&& listViews!=null)
            {
                this.list = list;
                this.listView = listViews;
            }
            bgWork.WorkerReportsProgress = true;
            bgWork.WorkerSupportsCancellation = true;
        }

        private void LoadDataWin_Loaded(object sender, RoutedEventArgs e)
        {
            int count = this.list.Count;
            this.totalCount.Content = "共计数据:  " +count + "条!";
            this.LoadDataPro.Maximum = count; //初始化Progress 控件的最大值
            bgWork.DoWork += BgWork_DoWork; //异步操作
            bgWork.RunWorkerAsync(); //开始异步执行
            bgWork.ProgressChanged += BgWork_ProgressChanged; //更新UI
            bgWork.RunWorkerCompleted += BgWork_RunWorkerCompleted; //操作完成 异常 取消事件 

        }
        //处理数据操作
        private void BgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;
            for (int i = 0; i <this.list.Count ; i++)
            {
                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                Thread.Sleep(1000);
                backgroundWorker.ReportProgress(i, new CommentModel(){ num=i, itemStr=this.list[i] });

            }
        }
        //取消操作
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            bgWork.CancelAsync();
        }
        //更新UI
        private void BgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            CommentModel commentModel = e.UserState as CommentModel;
            if (this.listView.Items.Add(commentModel.itemStr)>=0)
            {
                this.LoadDataPro.Value = e.ProgressPercentage;
                int count = commentModel.num;
                this.arealyNum.Content = "已加载:   " + count;
                this.noNum.Content = "未加载:    " + (this.list.Count - count);
            }
            else
            {
                MessageBox.Show(commentModel.itemStr+"项未加载!");
                return;
            }

        }
        //处理完成事件
        private void BgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) //任务取消
            {
                MessageBox.Show("任务取消执行!");
                this.Close();
            }
            else if (e.Error != null) //出现异常
            {
                MessageBox.Show("出现异常啦!" + e.Error.Message + e.Error.Source + e.Error.StackTrace);
            }
            else
            {
                this.DialogResult = true;
                this.Close(); //操作完成之后关闭窗口
            }
        }

    }
}

原文地址:https://www.cnblogs.com/lipengxu/p/10285516.html

时间: 2024-11-14 03:09:30

WPF BackGroundWord 异步加载更新进度条示例的相关文章

iOS 图片加载 圆形进度条

项目中有加载网络图片的需求,加一个加载的进度条会提高用户体验,网络不好的时候会清晰的看到图片加载的进度,比让用户看着满屏幕空白好.下面是我们项目自己封装的圆形进度条,分享给大家. 其实实现原理很简单,只是根据图片加载的进度来绘制一个圆. 先来看.h文件,需要一个进度的属性和进度条展示位置的方法: @property (nonatomic, assign) CGFloat progress; +(HMProgressView *)showHMProgressView:(UIView *)paren

Android利用Volley异步加载数据完整详细示例(二)

MainActivity如下: package cc.y; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.os.Bundle; import android.util.LruCache; import android.widget.ImageView;

Android利用Volley异步加载数据完整详细示例(一)

MainActivity如下: package cc.cn; import java.util.HashMap; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.os.Bundle; import com.android.volley.AuthFailureError; import com.android.volley.RequestQ

学习Echart:(二)异步加载更新

这部分比较简单,对图表的异步加载和更新,其实只是一部获取数据然后通过setOption传入数据和配置而已. $.get('data.json').done(function (data) { myChart.setOption({ title: { text: '异步数据加载示例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子&

【笔记】canvas图片预加载及进度条的实现

/*star *loading模块 *实现图片的预加载,并显示进度条 *参数:图片数组对象,加载完成的回调函数 */ function loadImages(sources,callback){ var loadedImages = 0; var numImages = 0; ctx.font='14px bold'; ctx.lineWidth=5; var clearWidth=canvas.width; var clearHeight=canvas.height; // get num o

VS2015 Cordova实现WebView加载页面进度条(Android)

因为使用Cordova做app时,加载页面没有进度条,用户无法感知打开进度,故加入进度条,具体实现如下: 1.  如果项目没有生成过apk,需先生成一次,这样在项目下面才会出现platforms/android的文件夹. 2.  进入项目/platforms/android/src文件夹下,在你程序包名目录下找到你的MainActivity.java文件,增加一个Dialog和ProgressBar用来显示页面加载进度,具体代码实现如下: 1 /* 2 Licensed to the Apach

cocos2dx 3.x(加载cocostudio进度条)

1 // 2 // MyLoagingScene.hpp 3 // My 4 // 5 // Created by work on 16/10/13. 6 // 7 // 8 9 #ifndef MyLoagingScene_hpp 10 #define MyLoagingScene_hpp 11 12 #include <stdio.h> 13 #include "cocos2d.h" 14 #include <editor-support/cocostudio/C

TangIDE开发技巧之自定义资源加载窗口进度条

用TangIDE开发游戏的朋友都知道,你可以像编辑普通的窗口一样编辑资源加载窗口,加入各种丰富的控件和动画效果,但是进度条相对比较单调,现在进度条默认是两张小图,加载时按九宫格来绘制,如果你不想用九宫格,想用两张水平长图替代它们,那么你可以在资源加载窗口的onSystemInit事件下,重写进度条控件(UIProgressBar)的drawBgImageH方法(这里的H表示水平形状的进度条),改变图片的绘制方式. var me = this; var win = this.getWindow()

js 多张图片加载 环形进度条

css 部分使用 svg 绘制环形 1 svg{width:100px; height: 100px; margin:15% auto 25%; box-sizing:border-box; display: block;} 2 svg circle{fill:none;cx:50;cy:50;} 3 /* svg text{x:40;y:55;} 不起作用 原因不知*/ 4 svg #txt{ x:35;y:55%;fill:red;} 5 svg #backdrop{stroke-linec