C# 通过事件传递参数
20200622
气死我了,一开始写的很详细,提交的时候因为长时间未操作提交失败了,今天懒得再写了,只把代码贴出来算了。
事件发布相关类:
public class ProEventArgs : EventArgs { public int percent; //事件参数重载 public ProEventArgs(int processNum) { percent = processNum; } } public class AlgoClass { public event EventHandler<ProEventArgs> NowProcessEvent; public void Calculate() { int progress = 0; for (int i = 0; i < 100; i++) { Thread.Sleep(30); progress = i + 1; NowProcessEvent(this, new ProEventArgs(progress)); } MessageBox.Show("!!!"); } }
事件订阅相关的类:
public partial class Form1 : Form { public Form1() { InitializeComponent(); progressBar1.Maximum = 100; progressBar1.Minimum = 0; action = (i) => { progressBar1.Value = i; }; } Action<int> action; private void button1_Click(object sender, EventArgs e) { AlgoClass algoClass = new AlgoClass(); Thread thread = new Thread(algoClass.Calculate); algoClass.NowProcessEvent += On_Procsee; thread.Start(); } public void On_Procsee(object sender, ProEventArgs e) { progressBar1.Invoke(action, e.percent); } }
这是个窗口应用程序,只看代码可能看不懂,放出VS项目文件:
详细的以后再更吧。。。或者不更了。。。