在界面开发过程中,会遇到耗时较长的处理过程,一般会将耗时较长的处理放到单独的线程中。然后在界面显示处理进度信息。
实现改效果的两种方式记录:
1. 使用委托:
//定义委托,在线程中使用 private delegate void SetProgressDelegate(int value, string text); private delegate void FinishDelegate(); public Form1() { InitializeComponent(); } private void btnStart_Click(object sender, EventArgs e) { //开启线程 new Thread(new ThreadStart(SubThread)).Start(); } //线程函数 private void SubThread() { FinishDelegate finish = new FinishDelegate(Finish); SetProgressDelegate setProgress = new SetProgressDelegate(SetProgress); for (int i = 0; i <= 100; i++) { //跨线程调用委托 this.Invoke(setProgress, new object[] { i, string.Format("{0}%", i) }); Thread.Sleep(100); //模拟耗时任务 } this.Invoke(finish); } private void SetProgress(int value, string text) { this.progressBar.Value = value; this.lblProgressText.Text = text; } private void Finish() { MessageBox.Show("处理完成!"); }
2. 使用异步线程上下文 SynchronizationContext
//UI线程的上下文 private SynchronizationContext mUIThreadSyncContext; public Form1() { InitializeComponent(); //初始化 mUIThreadSyncContext = SynchronizationContext.Current; } private void btnStart_Click(object sender, EventArgs e) { //开启线程 new Thread(new ThreadStart(SubThread)).Start(); } //线程函数 private void SubThread() { for (int i = 0; i <= 100; i++) { //更新UI线程 mUIThreadSyncContext.Post(new SendOrPostCallback(SetProgress), i); Thread.Sleep(100); //模拟耗时任务 } mUIThreadSyncContext.Post(new SendOrPostCallback(Finish), null); } private void SetProgress(object state) { this.progressBar.Value = Convert.ToInt32(state); this.lblProgressText.Text = state.ToString() + "%"; } private void Finish(object state) { MessageBox.Show("处理完成!"); }
原文地址:https://blog.csdn.net/tongxin1004/article/details/80979043
原文:https://www.cnblogs.com/runningRain/p/13719711.html