Suppose that there is a form F, which has a button BtnA and a Label control.
Requirements: click the button BtnA and display the status in Label according to the Start() method .
The resolution is to use the delegate or event .Let’s look at the following codes:
The form code:
private void BtnA_Click(object sender, EventArgs e)
{
A ms = new A();
ms.SetInfo += new EventHandler(ms_SetInfoTwo);
Thread m = new Thread(new ThreadStart(ms.Start));
m.Start();
}
private delegate void mySetInfo(string s);
void SetInfoOne(string s)
{
if (this.InvokeRequired)
{
this.Invoke(new mySetInfo(SetInfoOne), s);
return;
}
this.Label1.Text = s;
}
// event
void ms_SetInfoTwo(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new System.EventHandler(ms_SetInfoTwo), sender);
return;
}
this.Label1.Text = (string)sender;
}
Class A:
public class A
{
public event EventHandler SetInfo;
private void SetSourceInfo(object sender, EventArgs e)
{
if (SetInfo!= null) { SetInfo(sender, e); }
}
public dSetSourceInfo tt;
public delegate void dSetSourceInfo(string str);
private void SetSourceInfott(string str)
{
if (tt != null) { tt(str); }
}
public A() { }
/**////
/// Start
public void Start()
{
SetSourceInfo(“hahaha”,null);
Thread.Sleep(1000);
SetSourceInfo(“hahaha1″,null);
Thread.Sleep(1000);
SetSourceInfo(“hahaha2″,null);
}
}