今天写个个小程序.需要用到多线程.久了没有用,很模糊,现在花20分钟记录下.怕以后又忘记了.
写的时候.变量命名就没有过多考虑了,代码挺简单.就不加注释了.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace MultThread_Dlg { public partial class Form1 : Form { delegate void DgNum(string num); DgNum dgnum = null; delegate void DlgNum(string num); event DlgNum eventdlgNum = null; public Form1() { InitializeComponent(); dgnum = new DgNum(DoNum); eventdlgNum += new DlgNum(DoeventdlgNum); userControl11.dgClikeNode += new UserControl1.DGClikeNode(userControl11_dgClikeNode);//事件只能+= } #region "委托多线程" private void DoNum(Object str) { textBox1.Text = (string)str; } private void button1_Click(object sender, EventArgs e) { Thread td = new Thread(GetNum); td.Start(); } private void GetNum() { for (int i = 0; i < 100000; i++) { this.Invoke(dgnum, i.ToString()); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { System.Environment.Exit(-1); } #endregion #region "事件的使用" void DoeventdlgNum(object num) { textBox2.Text = num.ToString(); } private void button2_Click(object sender, EventArgs e) { Thread td = new Thread(EventNum); td.Start(); } private void EventNum() { for (int i = 0; i < 100000; i++) { this.Invoke(eventdlgNum, i.ToString());// } } void userControl11_dgClikeNode(string str) { MessageBox.Show(str); } #endregion } }
用户自定义控件使用委托
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace MultThread_Dlg { public partial class UserControl1 : UserControl { public delegate void DGClikeNode(string str); public event DGClikeNode dgClikeNode = null; public UserControl1() { InitializeComponent(); } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if (dgClikeNode != null) { dgClikeNode(e.Node.Text); } } } }
附上源码链接地址:https://files.cnblogs.com/xyong/MultThread_Dlg.zip
ps:多次点击new出的新线程也会阻塞主线程?