To communicate between two objects, we can use event or action to solve the problem. In the actual development process, when you need to call an Asynchronous Method in Class B in Class A, and then want the method in Class B to be executed to trigger some operations in Class, at this time, we should think of events.
Generally, we know the most about the control events, and the control events are triggered by external input. For example, when you click the control to trigger the event, the keyboard is triggered when there is a button. After an event is triggered, we can process and respond to the event in the eventhandle of the event registration. In fact, you can define events by yourself and trigger events in the form of code.
The following example describes how to communicate between two objects: the example is very simple.
1. Create a Windows application and drag and drop a control on form1 to test the event triggered by a custom event and to test the event with an action.
2. Create another actionevent. CS class that communicates with form1.cs;
First paste the Code:
Form1.cs:
Code
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;
Namespace eventtest
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Actionevent demo = new actionevent ();
// Register an event
Demo. eventaction + = delegate
{
MessageBox. Show ("OK ");
};
}
Private void button2_click (Object sender, eventargs E)
{
Actionevent demo = new actionevent ();
Action sysaction = delegate {MessageBox. Show ("OK ");};
Demo. systemaction = sysaction; // share an event Delegate
}
}
}
Eventaction. CS
Code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace eventtest
{
Class actionevent
{
Public Delegate void myaction ();
Public event myaction eventaction;
Public action systemaction {Get; set ;}
Public actionevent ()
{
System. Threading. Thread thread = new system. Threading. Thread (new system. Threading. threadstart (start ));
Thread. Start ();
}
Void start ()
{
System. Threading. thread. Sleep (3000 );
If (eventaction! = NULL)
Eventaction (); // trigger an event
If (systemaction! = NULL)
Systemaction (); // trigger an event
}
}
}
The actual example is as follows:
When event is used, when an event in the actionevent class is triggered, it will make all the delegates or methods in the class that have registered it respond to it;
When action was used at that time, two classes actually shared a delegate reference. When one of the references was triggered, the other was also stimulated.
This is a simple demo, which can often be used in asynchronous programming in projects :)