标签:nta min base names 控件 cti 异步 action ase
两个委托,一个委托(delegate)将值传到WinForm类,另一个委托(Action)更新UI
using System; using System.Windows.Forms; using System.Threading; namespace UpdateUIDemo { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } int p = 0; //声明一个委托,用来改变进度条状态 Action<int> Progress { get; set; } private void SetFormProgress(int p) { this.progressBar1.Minimum = 0; this.progressBar1.Maximum = 200000; this.progressBar1.Value = p; } private void SetProgress(object sender,object e) { p = Convert.ToInt32(e); //进度变化事件触发后,在这里触发更改进度条状态的Action委托 //子线程异步更改主线程控件UI,使用控件BeginInvoke方法,WPF为base.Dispatcher.BeginInvoke this.progressBar1.Invoke(Progress, p); } private void button1_Click(object sender, EventArgs e) { Work work = new Work(); //进度变化时触发的事件执行的方法 work.OnProgressChanged += SetProgress; //更改进度条 Progress += SetFormProgress; Thread t = new Thread(work.DoWork); t.Start(); } } class Work { // 声明一个监控进度变化的委托 public delegate void ProgressChangedHandler(object sender,object e); // 声明一个监控进度变化的事件 public event ProgressChangedHandler OnProgressChanged; //处理注册的事件 private void ProgressChanged(object sender,object e) { OnProgressChanged.Invoke(sender,e); } public void DoWork() { for (int i = 0; i <= 200000; i++) { ProgressChanged(this,i); } } } }
标签:nta min base names 控件 cti 异步 action ase
原文地址:https://www.cnblogs.com/yzhyingcool/p/10651717.html