Winform跨线程更新UI控件
2021-01-21 18:15
标签:method date csharp clean up 百分比 wing set 过程 sharp 首选拖几个控件,如图: 直接上代码: 页面设计器代码: 其它类: 效果图: 其它方式还有: 部分内容参考自:C# Winform 跨线程更新UI控件常用方法汇总 Winform跨线程更新UI控件 标签:method date csharp clean up 百分比 wing set 过程 sharp 原文地址:https://www.cnblogs.com/z415353144/p/12894230.html 1 public partial class Form3 : Form
2 {
3 public Form3()
4 {
5 InitializeComponent();
6 }
7
8
9 //方法一开始
10 private async void button1_Click(object sender, EventArgs e)
11 {
12 var t = Task.Run(() =>
13 {
14 Thread.Sleep(5000);
15 return "Hello I am TimeConsumingMethod";
16 });
17 label1.Text = await t;
18 }
19
20
21 private void btnWrite_Click(object sender, EventArgs e)
22 {
23 var taskCount = 10000; //任务量为10000
24 pgbWrite.Maximum = taskCount;
25 pgbWrite.Value = 0;
26
27 var dataWrite = new DataWrite(); //实例化一个写入数据的类
28 dataWrite.UpdateUIDelegate += UpdateUiStatus; //绑定更新任务状态的委托
29 dataWrite.TaskCallBack += Accomplish; //绑定完成任务要调用的委托
30
31 var thread = new Thread(dataWrite.Write) {IsBackground = true};
32 thread.Start(taskCount);
33 }
34
35 //更新UI
36 private void UpdateUiStatus(int step)
37 {
38 if (InvokeRequired)
39 {
40 Invoke(new AsycUpdateUi(delegate(int s)
41 {
42 pgbWrite.Value += s;
43 lblWriteStatus.Text = $"{pgbWrite.Value}/{pgbWrite.Maximum}";
44 }), step);
45 }
46 else
47 {
48 pgbWrite.Value += step;
49 lblWriteStatus.Text = $"{pgbWrite.Value}/{pgbWrite.Maximum}";
50 }
51 }
52
53 //完成任务时需要调用
54 private void Accomplish()
55 {
56 //还可以进行其他的一些完任务完成之后的逻辑处理
57 MessageBox.Show(@"任务完成");
58 }
59 //方法一结束
60
61 //方法三
62 private delegate void AsycUpdateUi(int step);
63
64
65 ////方法二开始
66 //private void button1_Click(object sender, EventArgs e)
67 //{
68 // var ResultTask = Task.Run(() => {
69 // Console.WriteLine("Helo I am TimeConsumingMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
70 // Thread.Sleep(5000);
71 // Console.WriteLine("Helo I am TimeConsumingMethod after Sleep(5000). My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
72 // return "Hello I am TimeConsumingMethod";
73 // });
74
75 // ResultTask.ContinueWith(OnDoSomthingIsComplete);
76
77 //}
78
79 //private void OnDoSomthingIsComplete(Task
1 partial class Form3
2 {
3 ///
public class DataWrite
{
public delegate void UpdateUI(int step);//声明一个更新主线程的委托
public UpdateUI UpdateUIDelegate;
public delegate void AccomplishTask();//声明一个在完成任务时通知主线程的委托
public AccomplishTask TaskCallBack;
public void Write(object lineCount)
{
StreamWriter writeIo = new StreamWriter("text.txt", false, Encoding.GetEncoding("gb2312"));
string head = "编号,省,市";
writeIo.Write(head);
for (int i = 0; i int)lineCount; i++)
{
writeIo.WriteLine(i.ToString() + ",北京,顺义");
//写入一条数据,调用更新主线程ui状态的委托
UpdateUIDelegate(1);
}
//任务完成时通知主线程作出相应的处理
TaskCallBack();
writeIo.Close();
}
}
//共分三步
//第一步:定义BackgroundWorker对象,并注册事件(执行线程主体、执行UI更新事件)
private BackgroundWorker backgroundWorker1 =null;
public Form1()
{
InitializeComponent();
backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
//设置报告进度更新
backgroundWorker1.WorkerReportsProgress = true;
//注册线程主体方法
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//注册更新UI方法
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
//backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
}
//第二步:定义执行线程主体事件
//线程主体方法
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//...执行线程任务
//在线程中更新UI(通过ReportProgress方法)
backgroundWorker1.ReportProgress(50, "This text was set safely by BackgroundWorker.");
//...执行线程其他任务
}
//第三步:定义执行UI更新事件
//UI更新方法
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.textBox1.Text = e.UserState.ToString();
}
//之后,启动线程
//启动backgroundWorker
private void setTextBackgroundWorkerBtn_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
/*
说明:C# Winform中执行异步任务时,BackgroundWorker是个不错的选择。它是EAP(Event based Asynchronous Pattern)思想的产物,DoWork用来执行异步任务,在任务执行过程中/执行完成后,我们可以通过ProgressChanged,ProgressCompleteded事件进行线程安全的UI更新。
需要注意的是://设置报告进度更新
backgroundWorker1.WorkerReportsProgress = true;
默认情况下BackgroundWorker是不报告进度的,需要显示设置报告进度属性。
*/
1 //共分三步
2 //第一步:获取UI线程同步上下文(在窗体构造函数或FormLoad事件中)
3 ///