WPF BackGroundWord 异步加载更新进度条示例
<Window x:Class="AsynchronousLoading.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:AsynchronousLoading"
mc:Ignorable="d"
Title="MainWindow" Height="" Width="" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen">
<Grid>
<ListView HorizontalAlignment="Left" x:Name="ItemListView" FontSize="" Width="" ></ListView> </Grid>
</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 = ; 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; }
}
}
<Window x:Class="AsynchronousLoading.GetDataWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:AsynchronousLoading"
mc:Ignorable="d"
Title="正在获取数据..." Height="" Width="" x:Name="GetDataWindow" Loaded="GetDataWindow_Loaded" WindowStartupLocation="CenterScreen">
<Grid>
<ProgressBar x:Name="GetDataPro" Height="" Minimum="" />
<Label x:Name="arealyNum" Content="已获得: 0" Height="" FontSize="" Foreground="Green" Margin="90,20,551,90"/>
<Label x:Name="noNum" Content="未获得: 0" Height="" FontSize="" Foreground="Red" Margin="291,10,345,79"/>
<Label x:Name="totalCount" Content="共计数据: 0 条" FontSize="" Height="" Margin="524,10,107,79"/>
<Button x:Name="btnCancel" Content="取消" FontSize="" Height="" Margin="347,81,297,18" Click="BtnCancel_Click" />
</Grid>
</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 = ; i < count; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
this.list.Add((i+).ToString());
backgroundWorker.ReportProgress(i,i.ToString());
Thread.Sleep();
}
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(); //操作完成之后关闭窗口
} } }
}
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 = ; i < count; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
this.list.Add((i+).ToString());
backgroundWorker.ReportProgress(i,i.ToString());
Thread.Sleep();
}
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(); //操作完成之后关闭窗口
} } }
}
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 = ; i <this.list.Count ; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
Thread.Sleep();
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)>=)
{
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(); //操作完成之后关闭窗口
}
} }
}
WPF BackGroundWord 异步加载更新进度条示例的更多相关文章
- android 网络异步加载数据进度条
ProgressDialog progressDialog = null; public static final int MESSAGETYPE = 0; private void execute( ...
- android AsyncTask异步下载并更新进度条
AsyncTask异步下载并更新进度条 //如果不是很明白请看上篇文章的异步下载 AsyncTask<String, Integer, String> 第一个参数:String 传入 ...
- js - 预加载+监听图片资源加载制作进度条
这两天遇到一个新需求:一个一镜到底的h5动画.因为功能的特殊性,就要求我们提前监听页面的静态图片是否全部加载完毕.即处理预加载. 总结下来,下次这种需求需要提前注意以下几点: 一.图片而不是背景图 本 ...
- 学习Echarts:(二)异步加载更新
这部分比较简单,对图表的异步加载和更新,其实只是异步获取数据然后通过setOption传入数据和配置而已. $.get('data.json').done(function (data) { myCh ...
- cocos2dx 3.x(加载cocostudio进度条)
// // MyLoagingScene.hpp // My // // Created by work on 16/10/13. // // #ifndef MyLoagingScene_hpp # ...
- js 多张图片加载 环形进度条
css 部分使用 svg 绘制环形 svg{width:100px; height: 100px; margin:15% auto 25%; box-sizing:border-box; displa ...
- 利用LruCache为GridView异步加载大量网络图片完整示例
MainActivity如下: package cc.testlrucache; import android.os.Bundle; import android.widget.GridView; i ...
- WebView长按保存图片;WebView不跳转到系统的浏览器;WebView加载显示进度条;WebView返回事件处理;
直接看代码即可,代码里面注释写的很清楚,这个类拉下来就能用: 写法和命名比较粗暴,但也简单易懂: public class MainActivity extends AppCompatActivity ...
- Unity异步加载场景loading条
using UnityEngine; using System.Collections; public class LoadingScene : MonoBehaviour { public UISl ...
随机推荐
- eclipse和sublime3打开freemarker(.ftl)文件
1.eclipse如何打开freemarker? https://jingyan.baidu.com/article/49ad8bce5ea95d5834d8fa9e.html 2.sublime3如 ...
- STM32CubeMX+Keil裸机代码风格(2)
10.找到STM32cubeMx所建的工程目录,在工程目录的同级目录下新建一个文件夹用来存放自己写的代码 11.用notepad++打开keil的工程文件,在这里的<Group>前面加上 ...
- Layui++>>ajax传递数组,防止深度序列化
- max (Largest elements in array)
句法: M = max(A) M = max(A,[],dim) [M,I] = max(___) C = max(A,B) ___ = max(___,nanflag) 描述: M=max(A) ...
- Debian中配置静态IP
默认安装Debian的时候是用dhcp服务的,有时我们需要设置一下静态IP. 一共涉及两个文件的修改 /etc/network/interfaces auto eth0#iface eth0 inet ...
- Photon自定义加载Resource之外的资源
PhotonNetwork.cs 结尾添加如下代码: #region >>> Photon自定义异步加载GameObject public delegate void CustomL ...
- Transaction rolled back because it has been marked as rollback-only
出现这种错误的原因 1.接口A 调用了接口B 2.接口B报异常了,没有在B里面进行try catch捕获 3.接口A对 接口B进行了try catch捕获 因为接口B报异常 会把当前事物A接口的事物( ...
- 安卓TabLayout+ViewPager实现切页
安卓使用TabLayout+ViewPager+Fragment 实现页面切换,可实现左右滑动切换视图界面和点击切换 可自定义菜单栏是在顶部还是在底部 一.实现效果: 二.实现过程: 2.1 一些重要 ...
- 【spring】从简单配置使用到深入
一.使用前的配置 1.maven引入需要的jar包 <properties> <spring.version>4.1.6.RELEASE</spring.version& ...
- Homebrew简介和基本使用
一.Homebrew是什么 Homebrew是一款Mac OS平台下的软件包管理工具,拥有安装.卸载.更新.查看.搜索等很多实用的功能.简单的一条指令,就可以实现包管理,而不用你关心各种依赖和文件路径 ...