WPF BackGroundWord 异步加载更新进度条示例
标签:threading horizon ogre out round close font xaml orm
1 "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 10 "Left " x:Name=" ItemListView " FontSize=" 30 " Width=" 389 " > 11
12 13
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
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public Liststring> list = new Liststring>();
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
{
///
/// 自定义传参类
///
public class CommentModel
{
///
/// 第几个
///
public int num { get ; set ; }
///
/// 当前添加的字符串项
///
public string itemStr { get ; set ; }
}
}
1 "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 10 "GetDataPro " Height=" 20 " Minimum=" 0 " />
11 "arealyNum " Content=" 已获得: 0 " Height=" 30 " FontSize=" 15 " Foreground=" Green " Margin=" 90,20,551,90 " />
12 "noNum " Content=" 未获得: 0 " Height=" 30 " FontSize=" 15 " Foreground=" Red " Margin=" 291,10,345,79 " />
13 "totalCount " Content=" 共计数据: 0 条 " FontSize=" 15 " Height=" 30 " Margin=" 524,10,107,79 " />
14 "btnCancel " Content=" 取消 " FontSize=" 15 " Height=" 20 " Margin=" 347,81,297,18 " Click=" BtnCancel_Click " />
15 16
using System;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System.Threading;
namespace AsynchronousLoading
{
///
/// GetDataWin.xaml 的交互逻辑
///
public partial class GetDataWin : Window
{
public Liststring> 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 )
{
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 ///
9 /// GetDataWin.xaml 的交互逻辑
10 ///
11 public partial class GetDataWin : Window
12 {
13 public Liststring> 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 )
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
{
///
/// LoadData.xaml 的交互逻辑
///
public partial class LoadData : Window
{
private ListView listView { get ; set ; } // 向列表中添加
private Liststring> list {get ;set ;} // 源数据集合
BackgroundWorker bgWork = new BackgroundWorker();
public LoadData(Liststring> 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(); // 操作完成之后关闭窗口
}
}
}
}
WPF BackGroundWord 异步加载更新进度条示例
标签:threading horizon ogre out round close font xaml orm
原文地址:https://www.cnblogs.com/lipengxu/p/10285516.html
评论