1 using System; 2 using System.Threading; 3 using System.Windows.Forms; 4 5 namespace 多线程 6 { 7 public partial class Form1 : Form 8 { 9 public Form1() 10 { 11 InitializeComponent(); 12 } 13 14 private void button1_Click(object sender, EventArgs e) 15 { 16 cDemo cd = new cDemo(); 17 cd.BoilerEventLog += wrt; 18 19 Thread thread = new Thread(cd.run); 20 thread.IsBackground = true; 21 thread.Start(); 22 } 23 24 delegate void WrtCallBack(string s); 25 public void wrt(string s) 26 { 27 if (richTextBox1.InvokeRequired) 28 { 29 WrtCallBack d = new WrtCallBack(wrt); 30 this.Invoke(d, new object[] { s }); 31 } 32 else 33 { 34 richTextBox1.AppendText(s + Environment.NewLine); 35 } 36 } 37 38 } 39 40 class cDemo 41 { 42 public event Action<string> BoilerEventLog; 43 public void run() 44 { 45 int i = 0; 46 do 47 { 48 BoilerEventLog?.Invoke(DateTime.Now.ToLongTimeString()); 49 i++; 50 Thread.Sleep(10); 51 } while (i < 200); 52 } 53 } 54 55 }
以上代码就是调用类的一个事件,在主线程获取事件返回,更新窗体内容,就是感觉代码冗余了,特别是在delegate void WrtCallBack(string s)处,看看大神有什么办法简化吗?
cDemo类来触发事件,Form1类来更新窗体对吗
using System; using System.Threading; using System.Windows.Forms; namespace 多线程 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { cDemo cd = new cDemo(); cd.BoilerEventLog += wrt; } public void wrt(string s) { if (this.InvokeRequired) { this.Invoke(new Action(wrt)); } else { richTextBox1.AppendText(s + Environment.NewLine); } } } class cDemo { public event Action<string> BoilerEventLog; public void run() { int i = 0; do { BoilerEventLog?.Invoke(DateTime.Now.ToLongTimeString()); i++; Thread.Sleep(10); } while (i < 200); } } }
@屋檐不懂雨: 是的,同时感谢回复。
但是您的方法编译不过,错误如附件截图,请帮忙再确认一下,谢谢!
@TabZ: 手残,打错了一点
using System; using System.Threading; using System.Windows.Forms; namespace 多线程 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { cDemo cd = new cDemo(); cd.BoilerEventLog += wrt; } public void wrt(string s) { if (this.InvokeRequired) { this.Invoke(new Action<string>(wrt)); } else { richTextBox1.AppendText(s + Environment.NewLine); } } } class cDemo { public event Action<string> BoilerEventLog; public void run() { int i = 0; do { BoilerEventLog?.Invoke(DateTime.Now.ToLongTimeString()); i++; Thread.Sleep(10); } while (i < 200); } } }
@屋檐不懂雨: 客气了!编译通过,功能正常,是我想要的,再次感谢!
我测试时 this.Invoke(new Action<string>(wrt)); 这里 报System.Reflection.TargetParameterCountException:“参数计数不匹配。”