namespace @delegate
{
public partial class Form1 : Form
{
private delegate void chang(object sender, myeventargs e);
private delegate void changedel(object sender, myeventargs e);
private event changedel events;
string b = "改变就是好事";
public Form1()
{
this.events+=new changedel(listen); //////////////////////////////订阅事件
InitializeComponent();
}
public class myeventargs : EventArgs
{
public string message;
public myeventargs(string a)
{
message = a;
}
}
public void eventing()
{
myeventargs mye = new myeventargs(b);
onevent(this, mye);
}
public void onevent(object sender, myeventargs e)
///////////////////////////////////////////包装成线程安全
{
if (events != null)
{
Delegate[] delegates = events.GetInvocationList();
/////////////////////////////////////////获取事件(委托对象)顺序调用多路广播委托的方法(本文中只有 changedel)
// Walk thru invocation list
foreach (changedel handler in delegates)
{
System.Windows.Forms.Control dispatcherObject = handler.Target as System.Windows.Forms.Control;
//////////////////////////////////////获取订阅handler的类对象
// If the subscriber is a DispatcherObject and different thread
if (dispatcherObject != null && dispatcherObject.InvokeRequired)
///////////////////////////需要委托
{
// Invoke handler in the target dispatcher's thread
dispatcherObject.Invoke(handler, this, e);
}
else // Execute handler as is
//////////////////////////不需要委托
{
events(this, e);
}
}
}
}
public void listen(object sender, myeventargs e) ///////////////////////////////////在子线程中改变主窗体控件属性(
注:如果不包装成线程安全就需要用委托)
{
{
this.label1.Text = e.message;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread tt = new Thread(new ThreadStart(this.eventing)); ///////////////////////////////////建立新线程触发自定义事件
tt.Start();
}
}
}